<?php

declare(strict_types=1);

namespace Tests\Unit;

use App\Models\Client;
use App\Models\ClientAddress;
use Illuminate\Database\Eloquent\Collection;
use PHPUnit\Framework\Attributes\Test;
use Tests\TestCase;

/**
 * Tests for Client::formatted_address — the single source of truth for the
 * client's display address across the PWA (collection cards, sync, detail).
 *
 * Uses the primary address, or falls back to the first one when none is marked
 * primary (tolerates rows saved without `is_primary`). No DB interaction — the
 * `addresses` relation is hydrated in memory.
 */
class ClientFormattedAddressTest extends TestCase
{
    /**
     * @param  array<int, ClientAddress>  $addresses
     */
    private function clientWithAddresses(array $addresses): Client
    {
        $client = new Client;
        $client->setRelation('addresses', new Collection($addresses));

        return $client;
    }

    #[Test]
    public function it_uses_the_primary_address(): void
    {
        $client = $this->clientWithAddresses([
            new ClientAddress(['address_line_1' => 'Calle 1', 'city' => 'Soledad', 'state' => 'Atlántico', 'is_primary' => false]),
            new ClientAddress(['address_line_1' => 'Carrera 2', 'city' => 'Barranquilla', 'state' => 'Atlántico', 'is_primary' => true]),
        ]);

        $this->assertSame('Carrera 2, Barranquilla, Atlántico', $client->formatted_address);
    }

    #[Test]
    public function it_falls_back_to_the_first_address_when_none_is_primary(): void
    {
        $client = $this->clientWithAddresses([
            new ClientAddress(['address_line_1' => 'Calle 1', 'city' => 'Soledad', 'state' => 'Atlántico', 'is_primary' => false]),
            new ClientAddress(['address_line_1' => 'Carrera 2', 'city' => 'Barranquilla', 'state' => 'Atlántico', 'is_primary' => false]),
        ]);

        $this->assertSame('Calle 1, Soledad, Atlántico', $client->formatted_address);
    }

    #[Test]
    public function it_returns_an_empty_string_when_there_are_no_addresses(): void
    {
        $client = $this->clientWithAddresses([]);

        $this->assertSame('', $client->formatted_address);
    }
}
