<?php

namespace Tests\Unit\Services\Fees;

use App\Services\Fees\FeeConfigService;
use App\Services\Fees\FeeGradeService;
use App\Services\Fees\FeeRefundCalculatorService;
use App\Services\Fees\FeeStudentFeeService;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\DB;
use Tests\TestCase;

class FeeRefundCalculatorServiceTest extends TestCase
{
    use RefreshDatabase;

    public function test_calculate_refund_caps_at_total_paid(): void
    {
        DB::table('configuration')->insert([
            ['config_key' => 'school_year', 'config_value' => '2025-2026'],
            ['config_key' => 'refund_deadline', 'config_value' => '2025-02-01'],
            ['config_key' => 'weeks_study', 'config_value' => '8'],
            ['config_key' => 'last_school_day', 'config_value' => '2025-06-01'],
            ['config_key' => 'first_student_fee', 'config_value' => '350'],
            ['config_key' => 'second_student_fee', 'config_value' => '200'],
            ['config_key' => 'youth_fee', 'config_value' => '180'],
        ]);

        DB::table('classSection')->insert([
            'id' => 1,
            'class_id' => 1,
            'class_section_id' => 101,
            'class_section_name' => '3',
            'semester' => 'Fall',
            'school_year' => '2025-2026',
        ]);

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

        DB::table('payments')->insert([
            'id' => 1,
            'parent_id' => 99,
            'invoice_id' => 1,
            'paid_amount' => 100.00,
            'total_amount' => 100.00,
            'balance' => 0.00,
            'number_of_installments' => 1,
            'payment_date' => '2025-01-10',
            'school_year' => '2025-2026',
            'status' => 'Paid',
        ]);

        $service = new FeeRefundCalculatorService(
            new FeeConfigService(),
            new FeeStudentFeeService(new FeeGradeService(), new FeeConfigService())
        );

        $result = $service->calculateRefund([
            [
                'student_id' => 1,
                'class_section_id' => 101,
                'enrollment_status' => 'withdrawn',
                'admission_status' => 'accepted',
                'withdrawal_date' => '2025-01-15',
            ],
        ], 99);

        $this->assertSame(100.0, $result['refund_amount']);
    }
}
