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

    public function test_index_returns_suppliers(): void
    {
        $user = $this->seedUser();
        $this->seedSupplier('Supplier A');

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

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

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

        Sanctum::actingAs($user);
        $response = $this->postJson('/api/v1/inventory/suppliers', [
            'name' => 'Supplier B',
            'email' => 'b@example.com',
        ]);

        $response->assertStatus(201);
        $this->assertDatabaseHas('suppliers', ['name' => 'Supplier B']);
    }

    public function test_update_changes_supplier(): void
    {
        $user = $this->seedUser();
        $supplierId = $this->seedSupplier('Supplier C');

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

        $response->assertOk();
        $this->assertDatabaseHas('suppliers', ['id' => $supplierId, 'name' => 'Supplier Updated']);
    }

    public function test_destroy_deletes_supplier(): void
    {
        $user = $this->seedUser();
        $supplierId = $this->seedSupplier('Supplier D');

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

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

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