<?php

namespace Tests\Unit\Services\Billing;

use App\Services\Billing\BalanceCalculationService;
use App\Services\Billing\BillingTotalsService;
use App\Services\Fees\FeeConfigService;
use App\Services\Fees\FeeGradeService;
use App\Services\Fees\FeeStudentFeeService;
use App\Services\Fees\TuitionCalculationService;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\DB;
use Tests\TestCase;

class BalanceCalculationServiceTest extends TestCase
{
    use RefreshDatabase;

    public function test_calculate_family_account_applies_balance_formula(): void
    {
        $this->seedFeeConfig();
        $this->seedClassSection(101, '2');
        $this->seedClassSection(102, '5');

        $parentId = 10;
        $invoiceId = $this->seedInvoice($parentId, 1000.00);

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

        DB::table('discount_usages')->insert([
            'voucher_id' => 1,
            'invoice_id' => $invoiceId,
            'parent_id' => $parentId,
            'discount_amount' => 80.00,
            'school_year' => '2025-2026',
            'semester' => 'Fall',
        ]);

        DB::table('additional_charges')->insert([
            'parent_id' => $parentId,
            'invoice_id' => $invoiceId,
            'school_year' => '2025-2026',
            'semester' => 'Fall',
            'charge_type' => 'add',
            'title' => 'Books',
            'amount' => 100.00,
            'status' => 'applied',
        ]);

        DB::table('events')->insert([
            'id' => 1,
            'event_name' => 'Field Trip',
            'amount' => 25.00,
            'expiration_date' => '2025-06-01',
        ]);

        DB::table('event_charges')->insert([
            'event_id' => 1,
            'parent_id' => $parentId,
            'student_id' => 2,
            'charged' => 50.00,
            'school_year' => '2025-2026',
            'semester' => 'Fall',
        ]);

        DB::table('refunds')->insert([
            'parent_id' => $parentId,
            'school_year' => '2025-2026',
            'invoice_id' => $invoiceId,
            'refund_amount' => 30.00,
            'refund_paid_amount' => 30.00,
            'status' => 'Paid',
            'semester' => 'Fall',
        ]);

        $service = $this->makeService();

        $result = $service->calculateFamilyAccount([
            [
                'student_id' => 1,
                'class_section_id' => 101,
                'enrollment_status' => 'enrolled',
                'admission_status' => 'accepted',
            ],
            [
                'student_id' => 2,
                'class_section_id' => 102,
                'enrollment_status' => 'enrolled',
                'admission_status' => 'accepted',
            ],
        ], $parentId);

        $this->assertSame($parentId, $result['parent_id']);
        $this->assertSame(550.0, $result['charges']['tuition']);
        $this->assertSame(100.0, $result['charges']['extra_charges']);
        $this->assertSame(50.0, $result['charges']['event_charges']);
        $this->assertSame(700.0, $result['charges']['total']);
        $this->assertSame(500.0, $result['payments']);
        $this->assertSame(80.0, $result['credits']['total']);
        $this->assertSame(30.0, $result['refunds_applied']);
        $this->assertSame(90.0, $result['remaining_balance']);
        $this->assertSame(0.0, $result['account_credit']);
        $this->assertCount(2, $result['students']);
    }

    public function test_overpayment_records_account_credit(): void
    {
        $this->seedFeeConfig();
        $this->seedClassSection(201, '3');

        $parentId = 20;
        $invoiceId = $this->seedInvoice($parentId, 500.00);

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

        $service = $this->makeService();

        $result = $service->calculateFamilyAccount([
            [
                'student_id' => 5,
                'class_section_id' => 201,
                'enrollment_status' => 'enrolled',
                'admission_status' => 'accepted',
            ],
        ], $parentId);

        $this->assertSame(350.0, $result['charges']['tuition']);
        $this->assertSame(0.0, $result['remaining_balance']);
        $this->assertSame(150.0, $result['account_credit']);
    }

    public function test_student_rows_include_event_charges(): void
    {
        $this->seedFeeConfig();
        $this->seedClassSection(301, '4');

        $parentId = 30;

        DB::table('events')->insert([
            'id' => 2,
            'event_name' => 'Camp',
            'amount' => 40.00,
            'expiration_date' => '2025-06-01',
        ]);
        DB::table('event_charges')->insert([
            'event_id' => 2,
            'parent_id' => $parentId,
            'student_id' => 7,
            'charged' => 40.00,
            'school_year' => '2025-2026',
        ]);

        $service = $this->makeService();

        $result = $service->calculateFamilyAccount([
            [
                'student_id' => 7,
                'firstname' => 'Sam',
                'lastname' => 'Lee',
                'class_section_id' => 301,
                'enrollment_status' => 'enrolled',
                'admission_status' => 'accepted',
            ],
        ], $parentId);

        $student = $result['students'][0];
        $this->assertSame(7, $student['student_id']);
        $this->assertSame(350.0, $student['tuition']);
        $this->assertSame(40.0, $student['event_charges']);
        $this->assertSame(390.0, $student['total_charges']);
    }

    private function makeService(): BalanceCalculationService
    {
        $config = new FeeConfigService();
        $tuition = new TuitionCalculationService(
            $config,
            new FeeStudentFeeService(new FeeGradeService(), $config)
        );

        return new BalanceCalculationService($config, $tuition, new BillingTotalsService());
    }

    private function seedFeeConfig(): void
    {
        DB::table('configuration')->insert([
            ['config_key' => 'school_year', 'config_value' => '2025-2026'],
            ['config_key' => 'first_student_fee', 'config_value' => '350'],
            ['config_key' => 'second_student_fee', 'config_value' => '200'],
            ['config_key' => 'youth_fee', 'config_value' => '180'],
        ]);
    }

    private function seedClassSection(int $sectionId, string $gradeName): void
    {
        DB::table('classSection')->insert([
            'class_id' => $sectionId,
            'class_section_id' => $sectionId,
            'class_section_name' => $gradeName,
            'semester' => 'Fall',
            'school_year' => '2025-2026',
        ]);
    }

    private function seedInvoice(int $parentId, float $total): int
    {
        return (int) DB::table('invoices')->insertGetId([
            'parent_id' => $parentId,
            'invoice_number' => 'INV-' . $parentId,
            'total_amount' => $total,
            'balance' => 0.00,
            'paid_amount' => 0.00,
            'issue_date' => '2025-01-01',
            'school_year' => '2025-2026',
            'semester' => 'Fall',
        ]);
    }
}
