<?php

declare(strict_types=1);

namespace ImovelZapAi\Properties\Application\Actions;

use ImovelZapAi\Properties\Domain\Enums\PropertyInterestSource;
use ImovelZapAi\Properties\Domain\Enums\PropertyInterestStatus;
use ImovelZapAi\Properties\Infrastructure\Persistence\Eloquent\PropertyInterestModel;
use ImovelZapAi\Properties\Infrastructure\Persistence\Eloquent\PropertyModel;
use ImovelZapAi\Tenancy\Support\TenantContext;

final class RegisterPropertyInterestAction
{
    public function execute(
        string $tenantId,
        string $contactId,
        string $propertyId,
        PropertyInterestSource $source,
        ?string $conversationId = null,
    ): PropertyInterestModel {
        TenantContext::set($tenantId);

        PropertyModel::query()
            ->where('tenant_id', $tenantId)
            ->whereKey($propertyId)
            ->firstOrFail();

        /** @var PropertyInterestModel|null $existing */
        $existing = PropertyInterestModel::query()
            ->where('tenant_id', $tenantId)
            ->where('contact_id', $contactId)
            ->where('property_id', $propertyId)
            ->first();

        if ($existing !== null) {
            $existing->update(array_filter([
                'conversation_id' => $conversationId ?? $existing->conversation_id,
                'source' => $source,
            ], static fn ($value): bool => $value !== null));

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

        /** @var PropertyInterestModel $interest */
        $interest = PropertyInterestModel::query()->create([
            'tenant_id' => $tenantId,
            'contact_id' => $contactId,
            'property_id' => $propertyId,
            'conversation_id' => $conversationId,
            'source' => $source,
            'status' => PropertyInterestStatus::New,
        ]);

        return $interest;
    }
}
