<?php

declare(strict_types=1);

namespace ImovelZapAi\Conversations\Application\Actions;

use ImovelZapAi\Conversations\Infrastructure\Persistence\Eloquent\ContactModel;

final class ResolveOrCreateContactAction
{
    public function execute(
        string $tenantId,
        string $waId,
        ?string $displayName = null,
    ): ContactModel {
        $normalizedName = $displayName !== null && trim($displayName) !== ''
            ? trim($displayName)
            : null;

        /** @var ContactModel $contact */
        $contact = ContactModel::query()->firstOrCreate(
            [
                'tenant_id' => $tenantId,
                'wa_id' => $waId,
            ],
            [
                'phone' => $waId,
                'display_name' => $normalizedName,
            ],
        );

        if ($normalizedName !== null && $contact->display_name !== $normalizedName) {
            $contact->update(['display_name' => $normalizedName]);
        }

        return $contact->fresh() ?? $contact;
    }
}
