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

    public function test_index_requires_authentication(): void
    {
        $response = $this->getJson('/api/v1/finance/refunds');

        $response->assertStatus(401);
    }

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

        DB::table('refunds')->insert([
            [
                'id' => 1,
                'parent_id' => 10,
                'school_year' => '2025-2026',
                'semester' => 'Fall',
                'refund_amount' => 50,
                'refund_paid_amount' => 0,
                'status' => 'Pending',
                'request' => 'overpayment',
                'created_at' => now(),
                'updated_at' => now(),
            ],
        ]);

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

        $response->assertOk();
        $response->assertJsonPath('ok', true);
        $response->assertJsonStructure([
            'ok',
            'refunds',
            'pagination' => [
                'current_page',
                'per_page',
                'total',
                'total_pages',
            ],
        ]);
    }

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

        DB::table('refunds')->insert([
            'id' => 1,
            'parent_id' => 10,
            'school_year' => '2025-2026',
            'semester' => 'Fall',
            'refund_amount' => 50,
            'refund_paid_amount' => 0,
            'status' => 'Pending',
            'request' => 'overpayment',
            'created_at' => now(),
            'updated_at' => now(),
        ]);

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

        $response->assertOk();
        $response->assertJsonPath('ok', true);
        $response->assertJsonStructure(['ok', 'refund' => ['id', 'status', 'refund_amount']]);
    }

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

        $this->seedConfig();

        DB::table('invoices')->insert([
            'id' => 1,
            'parent_id' => 10,
            'invoice_number' => 'INV-1',
            'total_amount' => 100.00,
            'balance' => 100.00,
            'paid_amount' => 0.00,
            'status' => 'Unpaid',
            'school_year' => '2025-2026',
            'semester' => 'Fall',
            'issue_date' => '2025-01-05',
        ]);

        DB::table('payments')->insert([
            'id' => 1,
            'parent_id' => 10,
            'invoice_id' => 1,
            'paid_amount' => 150.00,
            'total_amount' => 150.00,
            'balance' => 0.00,
            'payment_date' => '2025-01-10',
            'payment_method' => 'manual',
            'school_year' => '2025-2026',
            'semester' => 'Fall',
            'status' => 'Paid',
        ]);

        $response = $this->postJson('/api/v1/finance/refunds', [
            'parent_id' => 10,
            'request_type' => 'overpayment',
            'amount' => 25,
        ]);

        $response->assertStatus(201);
        $response->assertJsonPath('ok', true);
        $this->assertDatabaseHas('refunds', [
            'parent_id' => 10,
            'request' => 'overpayment',
        ]);
    }

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

        $response = $this->postJson('/api/v1/finance/refunds', [
            'parent_id' => 0,
            'request_type' => 'overpayment',
        ]);

        $response->assertStatus(422);
        $response->assertJsonStructure(['message', 'errors']);
    }

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

        DB::table('refunds')->insert([
            'id' => 1,
            'parent_id' => 10,
            'school_year' => '2025-2026',
            'semester' => 'Fall',
            'refund_amount' => 50,
            'refund_paid_amount' => 0,
            'status' => 'Pending',
            'request' => 'overpayment',
            'created_at' => now(),
            'updated_at' => now(),
        ]);

        $response = $this->patchJson('/api/v1/finance/refunds/1', [
            'status' => 'Approved',
            'reason' => 'ok',
        ]);

        $response->assertOk();
        $response->assertJsonPath('ok', true);
        $this->assertDatabaseHas('refunds', [
            'id' => 1,
            'status' => 'Approved',
        ]);
    }

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

        DB::table('refunds')->insert([
            'id' => 1,
            'parent_id' => 10,
            'school_year' => '2025-2026',
            'semester' => 'Fall',
            'refund_amount' => 50,
            'refund_paid_amount' => 0,
            'status' => 'Pending',
            'request' => 'overpayment',
            'created_at' => now(),
            'updated_at' => now(),
        ]);

        $response = $this->postJson('/api/v1/finance/refunds/1/reject', []);

        $response->assertStatus(422);
        $response->assertJsonStructure(['message', 'errors']);
    }

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

        DB::table('refunds')->insert([
            'id' => 1,
            'parent_id' => 10,
            'school_year' => '2025-2026',
            'semester' => 'Fall',
            'refund_amount' => 100,
            'refund_paid_amount' => 0,
            'status' => 'Approved',
            'request' => 'overpayment',
            'created_at' => now(),
            'updated_at' => now(),
        ]);

        $response = $this->postJson('/api/v1/finance/refunds/1/payments', [
            'paid_amount' => 40,
            'payment_method' => 'Cash',
        ]);

        $response->assertOk();
        $response->assertJsonPath('ok', true);
        $this->assertDatabaseHas('refunds', [
            'id' => 1,
            'status' => 'Partial',
        ]);
    }

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

        $this->seedConfig();

        DB::table('invoices')->insert([
            'id' => 1,
            'parent_id' => 10,
            'invoice_number' => 'INV-2',
            'total_amount' => 100.00,
            'balance' => 0.00,
            'paid_amount' => 100.00,
            'status' => 'Paid',
            'school_year' => '2025-2026',
            'semester' => 'Fall',
            'issue_date' => '2025-01-05',
        ]);

        DB::table('payments')->insert([
            'id' => 1,
            'parent_id' => 10,
            'invoice_id' => 1,
            'paid_amount' => 150.00,
            'total_amount' => 150.00,
            'balance' => 0.00,
            'payment_date' => '2025-01-10',
            'payment_method' => 'manual',
            'school_year' => '2025-2026',
            'semester' => 'Fall',
            'status' => 'Paid',
        ]);

        $response = $this->postJson('/api/v1/finance/refunds/recalculate-overpayments', []);

        $response->assertOk();
        $response->assertJsonPath('ok', true);
        $this->assertDatabaseHas('refunds', [
            'parent_id' => 10,
            'request' => 'overpayment',
        ]);
    }

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

        DB::table('refunds')->insert([
            'id' => 1,
            'parent_id' => 10,
            'school_year' => '2025-2026',
            'semester' => 'Fall',
            'refund_amount' => 50,
            'refund_paid_amount' => 0,
            'status' => 'Pending',
            'request' => 'overpayment',
            'created_at' => now(),
            'updated_at' => now(),
        ]);

        $response = $this->deleteJson('/api/v1/finance/refunds/1');

        $response->assertOk();
        $this->assertDatabaseHas('refunds', [
            'id' => 1,
            'status' => 'Canceled',
        ]);
    }

    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);
    }
}
