<?php

namespace Tests\Feature;

use App\Models\CorporateCompany;
use App\Models\CorporateEmployee;
use App\Models\Customer;
use App\Models\CustomerFamily;
use App\Models\Tenant;
use App\Models\User;
use App\Services\CustomerMergeService;
use App\Services\CustomerSearchService;
use App\Services\CustomerService;
use App\Services\MobileNormalizationService;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;

class CustomerAndCorporateMasterTest extends TestCase
{
    use RefreshDatabase;

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

    public function test_uae_mobile_normalization(): void
    {
        $res1 = MobileNormalizationService::normalize('0501234567');
        $this->assertEquals('971501234567', $res1['normalized_mobile']);

        $res2 = MobileNormalizationService::normalize('+971501234567');
        $this->assertEquals('971501234567', $res2['normalized_mobile']);

        $res3 = MobileNormalizationService::normalize('971501234567');
        $this->assertEquals('971501234567', $res3['normalized_mobile']);
    }

    public function test_customer_creation_and_phone_first_lookup(): void
    {
        $tenant = Tenant::first();
        $customerService = app(CustomerService::class);
        $searchService = app(CustomerSearchService::class);

        $customer = $customerService->createCustomer($tenant, [
            'first_name' => 'Rashid',
            'last_name' => 'Al Maktoum',
            'primary_mobile' => '0501112233',
            'passport_number' => 'Z99887766',
            'emirates_id' => '784-1990-1112233-1',
            'nationality' => 'Emirati',
        ]);

        $this->assertNotNull($customer);
        $this->assertStringStartsWith('CUS-', $customer->customer_code);

        // Test Phone-First Lookup
        $results = $searchService->search($tenant, '0501112233');
        $this->assertCount(1, $results['customers']);
        $this->assertEquals('Rashid Al Maktoum', $results['customers'][0]->full_name_en);
    }

    public function test_family_group_and_dependent_linking(): void
    {
        $tenant = Tenant::first();
        $customerService = app(CustomerService::class);

        $sponsor = $customerService->createCustomer($tenant, [
            'first_name' => 'Ahmed',
            'primary_mobile' => '0505556677',
        ]);

        $dependent = $customerService->createCustomer($tenant, [
            'first_name' => 'Fatima',
            'customer_type' => 'dependent',
            'primary_mobile' => '0505556677', // Shared family mobile
        ]);

        $family = CustomerFamily::create([
            'tenant_id' => $tenant->id,
            'family_code' => 'FAM-2026-0001',
            'family_name' => 'Ahmed Family',
            'primary_contact_customer_id' => $sponsor->id,
        ]);

        $this->assertNotNull($family);
        $this->assertEquals($sponsor->id, $family->primary_contact_customer_id);
    }

    public function test_corporate_company_and_corporate_employee_separation(): void
    {
        $tenant = Tenant::first();

        $company = CorporateCompany::create([
            'tenant_id' => $tenant->id,
            'company_code' => 'COM-2026-0001',
            'name_en' => 'Emirates Global Aluminum',
            'trade_license_number' => 'TL-789012',
            'status' => 'active',
        ]);

        $corpEmployee = CorporateEmployee::create([
            'tenant_id' => $tenant->id,
            'company_id' => $company->id,
            'corporate_employee_code' => 'CEMP-2026-0001',
            'full_name' => 'Anil Kumar',
            'passport_number' => 'P77665544',
            'status' => 'active',
        ]);

        $this->assertEquals($company->id, $corpEmployee->company_id);
        $this->assertDatabaseHas('corporate_employees', [
            'corporate_employee_code' => 'CEMP-2026-0001',
        ]);
    }

    public function test_controlled_customer_merge(): void
    {
        $tenant = Tenant::first();
        $user = User::where('tenant_id', $tenant->id)->first();
        $customerService = app(CustomerService::class);
        $mergeService = app(CustomerMergeService::class);

        $primary = $customerService->createCustomer($tenant, [
            'first_name' => 'Tariq',
            'primary_mobile' => '0509998877',
        ]);

        $duplicate = $customerService->createCustomer($tenant, [
            'first_name' => 'Tariq Dup',
            'primary_mobile' => '0509998877',
        ]);

        $mergeRecord = $mergeService->mergeCustomers($primary, $duplicate, 'Duplicate mobile number', $user);

        $this->assertNotNull($mergeRecord);
        $this->assertEquals('archived', $duplicate->fresh()->status);
        $this->assertTrue($duplicate->fresh()->trashed());
    }

    public function test_tenant_isolation_on_customer_search(): void
    {
        $tenantA = Tenant::first();
        $tenantB = Tenant::create([
            'company_name' => 'Isolated Tenant B',
            'slug' => 'isolated-b',
            'domain' => 'isolated-b.typingcenter.ae',
            'status' => 'active',
        ]);

        $customerService = app(CustomerService::class);
        $searchService = app(CustomerSearchService::class);

        $custA = $customerService->createCustomer($tenantA, [
            'first_name' => 'TenantA Customer',
            'primary_mobile' => '0501122334',
        ]);

        // Search Tenant B for Tenant A's customer mobile
        $resultsB = $searchService->search($tenantB, '0501122334');
        $this->assertCount(0, $resultsB['customers']);
    }
}
