<?php

namespace Tests\Feature;

use App\Models\LoanProduct;
use App\Models\Role;
use App\Models\User;
use Database\Seeders\DatabaseSeeder;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;

class LoanProductManagementTest extends TestCase
{
    use RefreshDatabase;

    protected function setUp(): void
    {
        parent::setUp();
        $this->seed(DatabaseSeeder::class);
    }

    public function test_super_administrator_can_create_product_and_action_is_audited(): void
    {
        $admin=User::where('email','admin@microfinance.local')->firstOrFail();
        $response=$this->actingAs($admin)->post(route('loan-products.store'),$this->payload());
        $product=LoanProduct::firstOrFail();
        $response->assertRedirect(route('loan-products.show',$product));
        $this->assertDatabaseHas('audit_logs',['action'=>'loan_product.created','auditable_id'=>$product->id]);
    }

    public function test_loan_officer_can_view_product_but_cannot_manage_it(): void
    {
        $user=User::factory()->create(['status'=>'active']);
        $user->roles()->attach(Role::where('name','loan-officer')->firstOrFail());
        $product=LoanProduct::factory()->create(['business_id'=>\App\Models\Business::firstOrFail()->id]);
        $this->actingAs($user)->get(route('loan-products.show',$product))->assertOk();
        $this->actingAs($user)->get(route('loan-products.edit',$product))->assertForbidden();
    }

    public function test_preview_uses_backend_engine_and_returns_reconciled_schedule(): void
    {
        $admin=User::where('email','admin@microfinance.local')->firstOrFail();
        $product=LoanProduct::factory()->create(['business_id'=>\App\Models\Business::firstOrFail()->id,'minimum_amount'=>'100.00','maximum_amount'=>'1000000.00','duration'=>4,'duration_unit'=>'weeks','repayment_frequency'=>'weekly','interest_rate'=>'10.000000']);
        $response=$this->actingAs($admin)->postJson(route('loan-products.preview',$product),['principal'=>'100000.00','start_date'=>'2026-08-01']);
        $response->assertOk()->assertJsonPath('summary.total_repayment','110000.00')->assertJsonCount(4,'installments');
    }

    private function payload(): array
    {
        return [
            'name'=>'One Month Standard','minimum_amount'=>'10000.00','maximum_amount'=>'1000000.00','duration'=>1,'duration_unit'=>'months',
            'interest_rate'=>'10.000000','interest_calculation_method'=>'flat','fixed_interest_amount'=>null,'repayment_frequency'=>'monthly','grace_period_days'=>0,
            'late_payment_penalty_type'=>'none','late_payment_penalty_value'=>'0.000000','processing_fee_type'=>'fixed','processing_fee_value'=>'1000.000000',
            'insurance_fee_type'=>'percentage','insurance_fee_value'=>'1.000000','other_charges'=>'500.00','collateral_required'=>'1','guarantor_required'=>'1','status'=>'active',
        ];
    }
}
