<?php

declare(strict_types=1);

namespace ImovelZapAi\Conversations\Application\Services;

use ImovelZapAi\Properties\Infrastructure\Persistence\Eloquent\PropertyInterestModel;
use ImovelZapAi\Properties\Infrastructure\Persistence\Eloquent\PropertyModel;

final class ConversationPropertyCodesQuery
{
    public function __construct(
        private readonly ConversationSummaryPresenter $presenter,
    ) {}

    /**
     * @param  list<string>  $propertyIds
     * @return list<string>
     */
    public function likedCodes(string $tenantId, string $contactId, string $conversationId, array $propertyIds): array
    {
        $fromInterests = PropertyInterestModel::query()
            ->where('tenant_id', $tenantId)
            ->where('contact_id', $contactId)
            ->where('conversation_id', $conversationId)
            ->with('property')
            ->get()
            ->map(fn (PropertyInterestModel $interest): string => $this->presenter->displayPropertyCode((string) $interest->property?->internal_code))
            ->filter()
            ->values()
            ->all();

        if ($fromInterests !== []) {
            return array_values(array_unique($fromInterests));
        }

        if ($propertyIds === []) {
            return [];
        }

        return PropertyModel::query()
            ->where('tenant_id', $tenantId)
            ->whereIn('id', $propertyIds)
            ->pluck('internal_code')
            ->map(fn (string $code): string => $this->presenter->displayPropertyCode($code))
            ->values()
            ->all();
    }

    /**
     * @param  list<string>  $propertyIds
     * @return list<string>
     */
    public function presentedCodes(string $tenantId, array $propertyIds): array
    {
        if ($propertyIds === []) {
            return [];
        }

        return PropertyModel::query()
            ->where('tenant_id', $tenantId)
            ->whereIn('id', $propertyIds)
            ->pluck('internal_code')
            ->map(fn (string $code): string => $this->presenter->displayPropertyCode($code))
            ->values()
            ->all();
    }
}
