<?php

use App\Models\Client;

test('primary_contact_email returns principal contact email', function () {
    $client = Client::factory()->create();
    $principal = $client->contacts->firstWhere('is_principal', true);

    expect($client->primary_contact_email)->toBe($principal->email);
});

test('primary_contact_email falls back to old contact_email column', function () {
    $client = Client::factory()->create([
        'contact_email' => 'fallback@test.com',
    ]);

    // Remove all contacts to force fallback
    $client->contacts()->delete();
    $client->unsetRelation('primaryContact');

    expect($client->primary_contact_email)->toBe('fallback@test.com');
});

test('primary_contact_email returns null when no contact exists', function () {
    $client = Client::factory()->create([
        'contact_email' => null,
    ]);

    $client->contacts()->delete();
    $client->unsetRelation('primaryContact');

    expect($client->primary_contact_email)->toBeNull();
});
