<?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 SupplyCategoriesControllerTest extends TestCase
{
    use RefreshDatabase;

    public function test_index_returns_categories(): void
    {
        $user = $this->seedUser();
        $this->seedCategory('Paper');

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

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

    public function test_store_creates_category(): void
    {
        $user = $this->seedUser();

        Sanctum::actingAs($user);
        $response = $this->postJson('/api/v1/inventory/supply-categories', [
            'name' => 'Cleaning',
        ]);

        $response->assertStatus(201);
        $this->assertDatabaseHas('supply_categories', ['name' => 'Cleaning']);
    }

    public function test_update_changes_category(): void
    {
        $user = $this->seedUser();
        $categoryId = $this->seedCategory('Pens');

        Sanctum::actingAs($user);
        $response = $this->patchJson('/api/v1/inventory/supply-categories/' . $categoryId, [
            'name' => 'Pens Updated',
        ]);

        $response->assertOk();
        $this->assertDatabaseHas('supply_categories', ['id' => $categoryId, 'name' => 'Pens Updated']);
    }

    public function test_destroy_deletes_category(): void
    {
        $user = $this->seedUser();
        $categoryId = $this->seedCategory('Markers');

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

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

    private function seedUser(): User
    {
        $userId = DB::table('users')->insertGetId([
            'firstname' => 'User',
            'lastname' => 'One',
            'cellphone' => '9999999999',
            'email' => 'supply@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 seedCategory(string $name): int
    {
        return DB::table('supply_categories')->insertGetId([
            'name' => $name,
            'created_at' => now(),
            'updated_at' => now(),
        ]);
    }
}
