<?php

namespace Tests\Feature\Api\V1\Finance;

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

class PurchaseOrderControllerTest extends TestCase
{
    use RefreshDatabase;

    public function test_index_returns_orders(): void
    {
        $this->seedUsers();
        $supplierId = DB::table('suppliers')->insertGetId(['name' => 'Alpha Supplies']);
        DB::table('purchase_orders')->insert([
            'id' => 1,
            'po_number' => 'PO-001',
            'supplier_id' => $supplierId,
            'status' => 'ordered',
            'subtotal' => 25,
            'tax' => 0,
            'total' => 25,
            'created_at' => now(),
            'updated_at' => now(),
        ]);

        Sanctum::actingAs(User::query()->findOrFail(1));

        $response = $this->getJson('/api/v1/finance/purchase-orders?q=PO-001');

        $response->assertOk();
        $response->assertJson(['ok' => true]);
        $this->assertNotEmpty($response->json('orders'));
    }

    public function test_options_returns_suppliers_and_supplies(): void
    {
        $this->seedUsers();
        DB::table('suppliers')->insert([
            ['id' => 1, 'name' => 'Alpha Supplies'],
            ['id' => 2, 'name' => 'Beta Supplies'],
        ]);
        DB::table('supplies')->insert([
            ['id' => 1, 'name' => 'Paper', 'unit' => 'box', 'qty_on_hand' => 0],
            ['id' => 2, 'name' => 'Ink', 'unit' => 'each', 'qty_on_hand' => 5],
        ]);

        Sanctum::actingAs(User::query()->findOrFail(1));

        $response = $this->getJson('/api/v1/finance/purchase-orders/options');

        $response->assertOk();
        $response->assertJson(['ok' => true]);
        $this->assertCount(2, $response->json('suppliers'));
        $this->assertCount(2, $response->json('supplies'));
    }

    public function test_store_creates_purchase_order_and_items(): void
    {
        $this->seedUsers();
        $supplierId = DB::table('suppliers')->insertGetId(['name' => 'Alpha Supplies']);
        $supplyId = DB::table('supplies')->insertGetId(['name' => 'Paper', 'unit' => 'box', 'qty_on_hand' => 0]);

        Sanctum::actingAs(User::query()->findOrFail(1));

        $response = $this->postJson('/api/v1/finance/purchase-orders', [
            'po_number' => 'PO-100',
            'supplier_id' => $supplierId,
            'order_date' => '2026-03-10',
            'expected_date' => '2026-03-15',
            'notes' => 'Initial order',
            'items' => [
                [
                    'supply_id' => $supplyId,
                    'description' => 'Paper for class',
                    'quantity' => 2,
                    'unit_cost' => 5,
                ],
            ],
        ]);

        $response->assertStatus(201);
        $response->assertJson(['ok' => true]);

        $this->assertDatabaseHas('purchase_orders', [
            'po_number' => 'PO-100',
            'supplier_id' => $supplierId,
            'subtotal' => 10,
            'total' => 10,
        ]);
        $this->assertDatabaseHas('purchase_order_items', [
            'supply_id' => $supplyId,
            'quantity' => 2,
            'unit_cost' => 5,
        ]);
    }

    public function test_receive_updates_inventory(): void
    {
        $this->seedUsers();
        $supplierId = DB::table('suppliers')->insertGetId(['name' => 'Alpha Supplies']);
        $supplyId = DB::table('supplies')->insertGetId(['name' => 'Paper', 'unit' => 'box', 'qty_on_hand' => 1]);
        $poId = DB::table('purchase_orders')->insertGetId([
            'po_number' => 'PO-200',
            'supplier_id' => $supplierId,
            'status' => 'ordered',
            'subtotal' => 20,
            'tax' => 0,
            'total' => 20,
            'created_at' => now(),
            'updated_at' => now(),
        ]);
        $itemId = DB::table('purchase_order_items')->insertGetId([
            'purchase_order_id' => $poId,
            'supply_id' => $supplyId,
            'description' => 'Paper for class',
            'quantity' => 4,
            'received_qty' => 0,
            'unit_cost' => 5,
            'created_at' => now(),
            'updated_at' => now(),
        ]);

        Sanctum::actingAs(User::query()->findOrFail(1));

        $response = $this->postJson("/api/v1/finance/purchase-orders/{$poId}/receive", [
            'items' => [
                ['id' => $itemId, 'quantity' => 4],
            ],
        ]);

        $response->assertOk();
        $response->assertJson(['ok' => true, 'completed' => true]);

        $this->assertDatabaseHas('purchase_order_items', [
            'id' => $itemId,
            'received_qty' => 4,
        ]);
        $this->assertDatabaseHas('supplies', [
            'id' => $supplyId,
            'qty_on_hand' => 5,
        ]);
        $this->assertDatabaseHas('supply_transactions', [
            'supply_id' => $supplyId,
            'type' => 'in',
            'quantity' => 4,
        ]);
    }

    public function test_cancel_marks_purchase_order(): void
    {
        $this->seedUsers();
        $supplierId = DB::table('suppliers')->insertGetId(['name' => 'Alpha Supplies']);
        $poId = DB::table('purchase_orders')->insertGetId([
            'po_number' => 'PO-300',
            'supplier_id' => $supplierId,
            'status' => 'ordered',
            'subtotal' => 0,
            'tax' => 0,
            'total' => 0,
            'created_at' => now(),
            'updated_at' => now(),
        ]);

        Sanctum::actingAs(User::query()->findOrFail(1));

        $response = $this->postJson("/api/v1/finance/purchase-orders/{$poId}/cancel");

        $response->assertOk();
        $response->assertJson(['ok' => true, 'status' => 'canceled']);
        $this->assertDatabaseHas('purchase_orders', [
            'id' => $poId,
            'status' => 'canceled',
        ]);
    }

    private function seedUsers(): void
    {
        DB::table('roles')->insert([
            ['id' => 1, 'name' => 'admin', 'slug' => 'admin', 'is_active' => 1],
        ]);

        DB::table('users')->insert([
            'id' => 1,
            'school_id' => 1,
            'firstname' => 'Admin',
            'lastname' => 'User',
            'cellphone' => '5555555555',
            'email' => 'admin@example.com',
            'address_street' => '123 Main',
            'city' => 'City',
            'state' => 'ST',
            'zip' => '12345',
            'accept_school_policy' => 1,
            'is_verified' => 1,
            'status' => 'Active',
            'is_suspended' => 0,
            'failed_attempts' => 0,
            'password' => bcrypt('secret'),
            'semester' => 'Fall',
            'school_year' => '2025-2026',
        ]);

        DB::table('user_roles')->insert([
            ['user_id' => 1, 'role_id' => 1],
        ]);
    }
}
