<?php

namespace Tests\Feature\Api\V1\Inventory;

use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\DB;
use Laravel\Sanctum\Sanctum;
use Tests\TestCase;

class InventoryItemsControllerTest extends TestCase
{
    use RefreshDatabase;

    public function test_index_returns_items(): void
    {
        $user = $this->seedUser();
        $this->seedConfig();
        $categoryId = $this->seedInventoryCategory('classroom');
        $this->seedInventoryItem($categoryId);

        Sanctum::actingAs($user);
        $response = $this->getJson('/api/v1/inventory/items?type=classroom');

        $response->assertOk();
        $response->assertJsonPath('status', true);
        $this->assertNotEmpty($response->json('data.items'));
    }

    public function test_show_returns_item(): void
    {
        $user = $this->seedUser();
        $this->seedConfig();
        $categoryId = $this->seedInventoryCategory('classroom');
        $itemId = $this->seedInventoryItem($categoryId);

        Sanctum::actingAs($user);
        $response = $this->getJson('/api/v1/inventory/items/' . $itemId);

        $response->assertOk();
        $response->assertJsonPath('status', true);
        $response->assertJsonPath('data.id', $itemId);
    }

    public function test_store_creates_item(): void
    {
        $user = $this->seedUser();
        $this->seedConfig();
        $categoryId = $this->seedInventoryCategory('classroom');

        Sanctum::actingAs($user);
        $response = $this->postJson('/api/v1/inventory/items', [
            'type' => 'classroom',
            'category_id' => $categoryId,
            'name' => 'Markers',
            'quantity' => 5,
            'condition' => 'good',
        ]);

        $response->assertStatus(201);
        $this->assertDatabaseHas('inventory_items', ['name' => 'Markers']);
        $this->assertDatabaseHas('inventory_movements', ['movement_type' => 'initial']);
    }

    public function test_update_changes_item(): void
    {
        $user = $this->seedUser();
        $this->seedConfig();
        $categoryId = $this->seedInventoryCategory('classroom');
        $itemId = $this->seedInventoryItem($categoryId);

        Sanctum::actingAs($user);
        $response = $this->patchJson('/api/v1/inventory/items/' . $itemId, [
            'name' => 'Updated Item',
        ]);

        $response->assertOk();
        $this->assertDatabaseHas('inventory_items', ['id' => $itemId, 'name' => 'Updated Item']);
    }

    public function test_destroy_deletes_item(): void
    {
        $user = $this->seedUser();
        $this->seedConfig();
        $categoryId = $this->seedInventoryCategory('classroom');
        $itemId = $this->seedInventoryItem($categoryId);

        Sanctum::actingAs($user);
        $response = $this->deleteJson('/api/v1/inventory/items/' . $itemId);

        $response->assertOk();
        $this->assertDatabaseMissing('inventory_items', ['id' => $itemId]);
    }

    public function test_audit_updates_classroom_item(): void
    {
        $user = $this->seedUser();
        $this->seedConfig();
        $categoryId = $this->seedInventoryCategory('classroom');
        $itemId = $this->seedInventoryItem($categoryId);

        Sanctum::actingAs($user);
        $response = $this->postJson('/api/v1/inventory/items/' . $itemId . '/audit', [
            'needs_repair_qty' => 1,
            'need_replace_qty' => 1,
            'cannot_find_qty' => 0,
        ]);

        $response->assertOk();
        $this->assertDatabaseHas('inventory_items', ['id' => $itemId, 'needs_repair_qty' => 1]);
    }

    public function test_adjust_creates_movement(): void
    {
        $user = $this->seedUser();
        $this->seedConfig();
        $categoryId = $this->seedInventoryCategory('classroom');
        $itemId = $this->seedInventoryItem($categoryId, 0);

        Sanctum::actingAs($user);
        $response = $this->postJson('/api/v1/inventory/items/' . $itemId . '/adjust', [
            'mode' => 'in',
            'quantity' => 2,
            'reason' => 'Restock',
        ]);

        $response->assertOk();
        $this->assertDatabaseHas('inventory_movements', ['item_id' => $itemId, 'movement_type' => 'in']);
    }

    public function test_summary_returns_aggregates(): void
    {
        $user = $this->seedUser();
        $this->seedConfig();
        $categoryId = $this->seedInventoryCategory('classroom');
        $this->seedInventoryItem($categoryId);

        Sanctum::actingAs($user);
        $response = $this->getJson('/api/v1/inventory/summary/classroom');

        $response->assertOk();
        $response->assertJsonPath('status', true);
        $this->assertNotEmpty($response->json('data.items'));
    }

    public function test_summary_all_returns_rows(): void
    {
        $user = $this->seedUser();
        $this->seedConfig();
        $categoryId = $this->seedInventoryCategory('classroom');
        $this->seedInventoryItem($categoryId);

        Sanctum::actingAs($user);
        $response = $this->getJson('/api/v1/inventory/summary-all');

        $response->assertOk();
        $response->assertJsonPath('status', true);
    }

    public function test_teacher_distribution_endpoints(): void
    {
        $user = $this->seedUser();
        $this->seedConfig();
        $this->seedTeacherRole($user->id);
        $classSectionId = $this->seedClassSection();
        $this->seedTeacherClass($user->id, $classSectionId);
        $studentId = $this->seedStudent(100, $user->id);
        $this->seedStudentClass($studentId, $classSectionId);
        $categoryId = $this->seedInventoryCategory('book');
        $bookId = $this->seedInventoryItem($categoryId, 5, 'book');

        Sanctum::actingAs($user);
        $formResponse = $this->getJson('/api/v1/inventory/teacher-distribution?class_section_id=' . $classSectionId . '&item_id=' . $bookId);
        $formResponse->assertOk();

        $storeResponse = $this->postJson('/api/v1/inventory/teacher-distribution', [
            'item_id' => $bookId,
            'class_section_id' => $classSectionId,
            'student_ids' => [$studentId],
        ]);
        $storeResponse->assertOk();
        $this->assertDatabaseHas('inventory_movements', ['item_id' => $bookId, 'movement_type' => 'distribution']);
    }

    public function test_validation_fails_for_store(): void
    {
        $user = $this->seedUser();
        Sanctum::actingAs($user);
        $response = $this->postJson('/api/v1/inventory/items', []);

        $response->assertStatus(422);
        $response->assertJsonPath('message', 'Validation failed.');
    }

    public function test_requires_authentication(): void
    {
        $response = $this->getJson('/api/v1/inventory/items');

        $response->assertStatus(401);
    }

    private function seedConfig(): void
    {
        DB::table('configuration')->insert([
            ['config_key' => 'school_year', 'config_value' => '2025-2026'],
            ['config_key' => 'semester', 'config_value' => 'Fall'],
        ]);
    }

    private function seedUser(): User
    {
        $userId = DB::table('users')->insertGetId([
            'firstname' => 'Teacher',
            'lastname' => 'User',
            'cellphone' => '9999999999',
            'email' => 'teacher@example.com',
            'address_street' => '123 Street',
            'city' => 'City',
            'state' => 'ST',
            'zip' => '12345',
            'accept_school_policy' => 1,
            'password' => bcrypt('password'),
            'user_type' => 'primary',
            'semester' => 'Fall',
            'school_year' => '2025-2026',
            'status' => 'Active',
        ]);

        return User::query()->findOrFail($userId);
    }

    private function seedInventoryCategory(string $type): int
    {
        return DB::table('inventory_categories')->insertGetId([
            'type' => $type,
            'name' => ucfirst($type) . ' Category',
            'created_at' => now(),
            'updated_at' => now(),
        ]);
    }

    private function seedInventoryItem(int $categoryId, int $quantity = 3, string $type = 'classroom'): int
    {
        return DB::table('inventory_items')->insertGetId([
            'type' => $type,
            'category_id' => $categoryId,
            'name' => 'Item ' . $type,
            'quantity' => $quantity,
            'semester' => 'Fall',
            'school_year' => '2025-2026',
            'created_at' => now(),
            'updated_at' => now(),
        ]);
    }

    private function seedTeacherRole(int $userId): void
    {
        $roleId = DB::table('roles')->insertGetId([
            'name' => 'teacher',
            'dashboard_route' => 'teacher',
            'priority' => 1,
            'is_active' => 1,
        ]);

        DB::table('user_roles')->insert([
            'user_id' => $userId,
            'role_id' => $roleId,
            'created_at' => now(),
            'updated_at' => now(),
        ]);
    }

    private function seedClassSection(): int
    {
        DB::table('classes')->insert([
            'id' => 1,
            'class_name' => 'Grade 1',
            'created_at' => now(),
            'updated_at' => now(),
        ]);

        DB::table('classSection')->insert([
            'class_section_id' => 200,
            'class_section_name' => 'Grade 1',
            'class_id' => 1,
            'semester' => 'Fall',
            'school_year' => '2025-2026',
            'created_at' => now(),
            'updated_at' => now(),
        ]);

        return 200;
    }

    private function seedTeacherClass(int $userId, int $classSectionId): void
    {
        DB::table('teacher_class')->insert([
            'teacher_id' => $userId,
            'class_section_id' => $classSectionId,
            'position' => 'main',
            'school_year' => '2025-2026',
            'created_at' => now(),
            'updated_at' => now(),
        ]);
    }

    private function seedStudent(int $id, int $parentId): int
    {
        DB::table('students')->insert([
            'id' => $id,
            'school_id' => 'SCH1',
            'firstname' => 'Student',
            'lastname' => 'One',
            'age' => 10,
            'gender' => 'Male',
            'photo_consent' => 1,
            'parent_id' => $parentId,
            'year_of_registration' => '2025-2026',
            'semester' => 'Fall',
            'school_year' => '2025-2026',
            'is_active' => 1,
        ]);

        return $id;
    }

    private function seedStudentClass(int $studentId, int $classSectionId): void
    {
        DB::table('student_class')->insert([
            'student_id' => $studentId,
            'class_section_id' => $classSectionId,
            'school_year' => '2025-2026',
            'semester' => 'Fall',
            'is_event_only' => 0,
            'created_at' => now(),
            'updated_at' => now(),
        ]);
    }
}
