<?php

namespace Tests\Feature;

use App\Models\Branch;
use App\Models\Business;
use App\Models\Customer;
use App\Models\User;
use Database\Seeders\DatabaseSeeder;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;

class LoanInlineCreateTest extends TestCase
{
    use RefreshDatabase;

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

    public function test_new_loan_application_contains_inline_customer_guarantor_and_collateral_forms(): void
    {
        $business = Business::firstOrFail();
        Branch::create(['business_id' => $business->id, 'name' => 'Inline Create Branch', 'status' => 'active']);
        $admin = User::where('email', 'admin@microfinance.local')->firstOrFail();

        $this->actingAs($admin)->get(route('loans.create'))
            ->assertOk()
            ->assertSee('id="quick-customer-dialog"', false)
            ->assertSee('name="next_of_kin_name"', false)
            ->assertSee('id="quick-guarantor-dialog"', false)
            ->assertSee('name="signed_guarantee"', false)
            ->assertSee('id="quick-collateral-dialog"', false)
            ->assertSee('name="serial_number"', false)
            ->assertSee("plusButton('customer'", false)
            ->assertSee("plusButton('guarantor'", false)
            ->assertSee("plusButton('collateral'", false);
    }

    public function test_guarantor_store_returns_created_record_for_inline_selection_when_json_is_requested(): void
    {
        $business = Business::firstOrFail();
        $branch = Branch::create(['business_id' => $business->id, 'name' => 'Guarantor Inline Branch', 'status' => 'active']);
        $customer = Customer::create([
            'branch_id' => $branch->id,
            'customer_number' => 'CUS-INLINE-001',
            'identity_mode' => 'without_nin',
            'first_name' => 'Asha',
            'last_name' => 'Mushi',
            'phone' => '0712000001',
            'status' => 'active',
        ]);
        $admin = User::where('email', 'admin@microfinance.local')->firstOrFail();

        $this->actingAs($admin)->postJson(route('customers.guarantors.store', $customer), [
            'full_name' => 'Neema Mushi',
            'nin' => '19900101-12345-00001-01',
            'phone' => '0712000002',
            'relationship' => 'Sister',
            'occupation' => 'Teacher',
            'address' => 'Dodoma',
        ])->assertCreated()
            ->assertJsonPath('guarantor.customer_id', $customer->id)
            ->assertJsonPath('guarantor.full_name', 'Neema Mushi')
            ->assertJsonPath('guarantor.phone', '255712000002');

        $this->assertDatabaseHas('guarantors', [
            'customer_id' => $customer->id,
            'full_name' => 'Neema Mushi',
            'phone' => '255712000002',
        ]);
    }
}
