<?php

namespace Tests\Feature\Api\V1\Finance;

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

class ChargeControllerTest extends TestCase
{
    use RefreshDatabase;

    protected function tearDown(): void
    {
        Mockery::close();
        parent::tearDown();
    }

    protected function setUp(): void
    {
        parent::setUp();

        $this->mock(InvoiceGenerationService::class, function ($mock) {
            $mock->shouldReceive('generateInvoice')->andReturn(['ok' => true]);
        });
    }

    public function test_list_charges_for_parent(): void
    {
        $user = $this->createUser();
        Sanctum::actingAs($user);
        $this->seedConfig();

        DB::table('additional_charges')->insert([
            'parent_id' => 10,
            'school_year' => '2025-2026',
            'semester' => 'Fall',
            'charge_type' => 'add',
            'title' => 'Books',
            'amount' => 20.00,
            'status' => 'pending',
        ]);

        $response = $this->getJson('/api/v1/finance/fees/charges?parent_id=10');

        $response->assertOk();
        $response->assertJsonPath('ok', true);
        $this->assertCount(1, $response->json('charges.extra_charges'));
    }

    public function test_store_extra_charge_returns_409_on_duplicate(): void
    {
        $user = $this->createUser();
        Sanctum::actingAs($user);
        $this->seedConfig();

        DB::table('additional_charges')->insert([
            'parent_id' => 10,
            'school_year' => '2025-2026',
            'semester' => 'Fall',
            'charge_type' => 'add',
            'title' => 'Books',
            'amount' => 20.00,
            'status' => 'pending',
        ]);

        $response = $this->postJson('/api/v1/finance/fees/charges/extra', [
            'parent_id' => 10,
            'title' => 'Books',
            'amount' => 20,
            'charge_type' => 'add',
        ]);

        $response->assertStatus(409);
        $response->assertJsonPath('ok', false);
        $response->assertJsonPath('charge.error', 'duplicate_charge');
    }

    public function test_store_event_charge_creates_row(): void
    {
        $user = $this->createUser();
        Sanctum::actingAs($user);
        $this->seedConfig();

        $response = $this->postJson('/api/v1/finance/fees/charges/event', [
            'parent_id' => 10,
            'student_id' => 1,
            'event_name' => 'Science Fair',
            'amount' => 15,
        ]);

        $response->assertStatus(201);
        $response->assertJsonPath('ok', true);
        $this->assertDatabaseHas('event_charges', [
            'parent_id' => 10,
            'student_id' => 1,
            'event_name' => 'Science Fair',
        ]);
    }

    public function test_cancel_extra_charge_voids_row(): void
    {
        $user = $this->createUser();
        Sanctum::actingAs($user);
        $this->seedConfig();

        $id = DB::table('additional_charges')->insertGetId([
            'parent_id' => 10,
            'school_year' => '2025-2026',
            'semester' => 'Fall',
            'charge_type' => 'add',
            'title' => 'Fee',
            'amount' => 10.00,
            'status' => 'pending',
        ]);

        $response = $this->postJson("/api/v1/finance/fees/charges/extra/{$id}/cancel");

        $response->assertOk();
        $this->assertDatabaseHas('additional_charges', ['id' => $id, 'status' => 'void']);
    }

    public function test_charges_endpoints_require_authentication(): void
    {
        $response = $this->getJson('/api/v1/finance/fees/charges?parent_id=10');
        $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 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);
    }
}
