<?php

namespace Tests\Feature;

use App\Models\LoanProduct;
use App\Models\User;
use App\Services\LoanCalculationService;
use Carbon\CarbonImmutable;
use Database\Seeders\DatabaseSeeder;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;

class ProcessingFeePaymentModeTest extends TestCase
{
    use RefreshDatabase;

    public function test_processing_fee_modes_change_repayment_and_customer_disbursement_correctly(): void
    {
        $calculator = app(LoanCalculationService::class);
        $product = new LoanProduct([
            'minimum_amount'=>'100.00','maximum_amount'=>'10000.00','duration'=>1,'duration_unit'=>'months',
            'interest_rate'=>'0','interest_calculation_method'=>'flat','repayment_frequency'=>'monthly','grace_period_days'=>0,
            'processing_fee_type'=>'fixed','processing_fee_value'=>'100.00','insurance_fee_type'=>'fixed','insurance_fee_value'=>'0',
            'other_charges'=>'0',
        ]);

        $product->processing_fee_payment_mode='financed';
        $financed=$calculator->calculate($product,'1000.00',CarbonImmutable::parse('2026-09-01'));
        $this->assertSame('100.00',$financed['fees']);
        $this->assertSame('1100.00',$financed['total_repayment']);
        $this->assertSame('1000.00',$financed['net_disbursement']);
        $this->assertSame('0.00',$financed['processing_fee_cash_due']);

        $product->processing_fee_payment_mode='deducted';
        $deducted=$calculator->calculate($product,'1000.00',CarbonImmutable::parse('2026-09-01'));
        $this->assertSame('0.00',$deducted['fees']);
        $this->assertSame('1000.00',$deducted['total_repayment']);
        $this->assertSame('900.00',$deducted['net_disbursement']);
        $this->assertSame('0.00',$deducted['processing_fee_cash_due']);

        $product->processing_fee_payment_mode='cash';
        $cash=$calculator->calculate($product,'1000.00',CarbonImmutable::parse('2026-09-01'));
        $this->assertSame('0.00',$cash['fees']);
        $this->assertSame('1000.00',$cash['total_repayment']);
        $this->assertSame('1000.00',$cash['net_disbursement']);
        $this->assertSame('100.00',$cash['processing_fee_cash_due']);
    }

    public function test_loan_product_form_requires_a_visible_processing_fee_payment_choice(): void
    {
        $this->seed(DatabaseSeeder::class);
        $admin=User::where('email','admin@microfinance.local')->firstOrFail();

        $this->actingAs($admin)->get(route('loan-products.create'))
            ->assertOk()
            ->assertSee('How processing fee is paid')
            ->assertSee('Paid cash upfront')
            ->assertSee('Deduct from disbursement')
            ->assertSee('Include in loan repayments');
    }
}
