<?php

namespace Tests\Feature;

use App\Contracts\NationalIdentityProvider;
use App\Models\Business;
use App\Models\Setting;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Http;
use Tests\TestCase;

class NidaLookupIntegrationTest extends TestCase
{
    use RefreshDatabase;

    public function test_nida_lookup_is_disabled_by_default_and_makes_no_external_request(): void
    {
        Http::fake();

        $provider = app(NationalIdentityProvider::class);

        $this->assertFalse($provider->isConfigured());
        $this->assertNull($provider->lookup('19900101123456789012'));
        Http::assertNothingSent();
    }

    public function test_enabled_nida_lookup_normalizes_provider_response_for_customer_form(): void
    {
        $business = Business::firstOrCreate(['id' => 1], ['name' => 'Microfinance']);
        Setting::updateOrCreate(
            ['business_id' => $business->id, 'group' => 'identity', 'key' => 'nin_lookup_enabled'],
            ['value' => '1', 'type' => 'boolean'],
        );

        config([
            'nida.lookup_base_url' => 'https://ors.brela.go.tz/um/load/load_nida',
            'nida.timeout_seconds' => 15,
            'nida.connect_timeout_seconds' => 5,
        ]);

        Http::fake([
            'https://ors.brela.go.tz/um/load/load_nida/*' => Http::response([
                'obj' => [
                    'Nin' => '19900101123456789012',
                    'Firstname' => 'AMINA',
                    'Middlename' => 'JUMA',
                    'Surname' => 'MWAKALINGA',
                    'Sex' => 'FEMALE',
                    'Dateofbirth' => '1990-01-01',
                    'Phonenumber' => '0712345678',
                    'Occupation' => 'TRADER',
                    'Maritalstatus' => 'MARRIED',
                    'Residentregion' => 'DODOMA',
                    'Residentdistrict' => 'DODOMA CBD',
                    'Residentward' => 'MAKUTUPORA',
                    'Residentvillage' => 'MAKUTUPORA',
                    'Residenthouseno' => '12',
                ],
            ], 200),
        ]);

        $provider = app(NationalIdentityProvider::class);
        $identity = $provider->lookup('19900101123456789012');

        $this->assertTrue($provider->isConfigured());
        $this->assertSame('AMINA', $identity['first_name']);
        $this->assertSame('JUMA', $identity['middle_name']);
        $this->assertSame('MWAKALINGA', $identity['last_name']);
        $this->assertSame('female', $identity['gender']);
        $this->assertSame('1990-01-01', $identity['date_of_birth']);
        $this->assertSame('married', $identity['marital_status']);
        $this->assertSame('DODOMA', $identity['region']);

        Http::assertSent(fn ($request): bool =>
            $request->method() === 'POST'
            && $request->url() === 'https://ors.brela.go.tz/um/load/load_nida/19900101123456789012'
        );
    }
}
