<?php

namespace Tests\Unit\Services\Refunds;

use App\Services\Fees\FeeRefundDetailService;
use App\Services\Refunds\RefundInvoiceAdjustmentService;
use App\Services\Refunds\RefundNotificationService;
use App\Services\Refunds\RefundPolicyService;
use App\Services\Refunds\RefundRequestService;
use App\Services\Refunds\RefundSummaryService;
use App\Services\Discounts\DiscountInvoiceService;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\DB;
use Tests\TestCase;

class RefundRequestServiceTest extends TestCase
{
    use RefreshDatabase;

    public function test_request_overpayment_creates_refund(): void
    {
        DB::table('configuration')->insert([
            ['config_key' => 'school_year', 'config_value' => '2025-2026'],
            ['config_key' => 'semester', 'config_value' => 'Fall'],
        ]);

        DB::table('users')->insert([
            'id' => 10,
            'firstname' => 'Parent',
            'lastname' => 'User',
            'email' => 'parent@example.com',
            'status' => 'Active',
        ]);

        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',
            'school_year' => '2025-2026',
            'semester' => 'Fall',
            'status' => 'Paid',
        ]);

        $service = new RefundRequestService(
            new RefundPolicyService(
                new FeeRefundDetailService(),
                new RefundInvoiceAdjustmentService(new DiscountInvoiceService())
            ),
            new RefundSummaryService(),
            new RefundNotificationService()
        );

        $result = $service->requestRefund([
            'parent_id' => 10,
            'request_type' => 'overpayment',
            'amount' => 25,
        ], 1);

        $this->assertTrue($result['ok']);
        $this->assertDatabaseHas('refunds', [
            'parent_id' => 10,
            'request' => 'overpayment',
        ]);
    }
}
