<?php

namespace Tests\Feature\Api\V1\Expenses;

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

class ExpenseControllerTest extends TestCase
{
    use RefreshDatabase;

    public function test_options_returns_staff_and_retailors(): void
    {
        $this->seedStaffUsers();

        $user = $this->createUser();
        Sanctum::actingAs($user);

        $response = $this->getJson('/api/v1/expenses/options');

        $response->assertOk();
        $this->assertNotEmpty($response->json('staff'));
        $this->assertNotEmpty($response->json('retailors'));
    }

    public function test_store_creates_expense(): void
    {
        $this->seedStaffUsers();

        Storage::fake();

        $user = $this->createUser();
        Sanctum::actingAs($user);

        $file = UploadedFile::fake()->create('receipt.pdf', 10, 'application/pdf');

        $response = $this->post('/api/v1/expenses', [
            'category' => 'Expense',
            'amount' => 25.5,
            'purchased_by' => 2,
            'retailor' => 'Amazon',
            'date_of_purchase' => '2025-09-01',
            'description' => 'Supplies',
            'receipt' => $file,
        ], ['Accept' => 'application/json']);

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

        $this->assertDatabaseHas('expenses', [
            'category' => 'Expense',
            'purchased_by' => 2,
        ]);
    }

    public function test_index_lists_expenses(): void
    {
        $this->seedExpenseData();

        $user = $this->createUser();
        Sanctum::actingAs($user);

        $response = $this->getJson('/api/v1/expenses');

        $response->assertOk();
        $this->assertNotEmpty($response->json('expenses'));
    }

    public function test_show_returns_expense(): void
    {
        $this->seedExpenseData();

        $user = $this->createUser();
        Sanctum::actingAs($user);

        $response = $this->getJson('/api/v1/expenses/1');

        $response->assertOk();
        $response->assertJson([
            'ok' => true,
            'expense' => [
                'id' => 1,
                'category' => 'Expense',
            ],
        ]);
    }

    public function test_update_status_changes_status(): void
    {
        $this->seedExpenseData();

        $user = $this->createUser();
        Sanctum::actingAs($user);

        $response = $this->postJson('/api/v1/expenses/1/status', [
            'status' => 'approved',
            'reason' => 'Ok',
        ]);

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

        $this->assertDatabaseHas('expenses', [
            'id' => 1,
            'status' => 'approved',
        ]);
    }

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

        DB::table('users')->insert([
            [
                'id' => 2,
                'school_id' => 1,
                'firstname' => 'Staff',
                'lastname' => 'User',
                'cellphone' => '5555555555',
                'email' => 'staff@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',
            ],
            [
                'id' => 3,
                'school_id' => 1,
                'firstname' => 'Parent',
                'lastname' => 'User',
                'cellphone' => '5555555555',
                'email' => 'parent@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' => 2, 'role_id' => 1],
            ['user_id' => 3, 'role_id' => 2],
        ]);
    }

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

        DB::table('users')->insert([
            'id' => 2,
            'school_id' => 1,
            'firstname' => 'Staff',
            'lastname' => 'User',
            'cellphone' => '5555555555',
            'email' => 'staff@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('expenses')->insert([
            'id' => 1,
            'category' => 'Expense',
            'amount' => 10,
            'date_of_purchase' => '2025-09-01',
            'purchased_by' => 2,
            'added_by' => 1,
            'school_year' => '2025-2026',
            'semester' => 'Fall',
            'status' => 'pending',
        ]);
    }

    private function createUser(): User
    {
        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',
        ]);

        return User::query()->findOrFail(1);
    }
}
