<?php

declare(strict_types=1);

namespace ImovelZapAi\Publishing\Connectors\GroupOlx\Application\Queries;

use ImovelZapAi\Properties\Infrastructure\Persistence\Eloquent\PropertyModel;
use ImovelZapAi\Publishing\Connectors\GroupOlx\Application\Ports\PublishedGroupOlxPropertiesQueryInterface;
use ImovelZapAi\Publishing\Connectors\GroupOlx\Domain\GroupOlxConnector;
use ImovelZapAi\Publishing\Domain\Enums\PublicationTargetStatus;
use ImovelZapAi\Publishing\Infrastructure\Persistence\Eloquent\PublicationModel;

/**
 * Imóveis publicados no canal Grupo OLX (ou xml_export enquanto o canal não é provisionado).
 */
final class PublishedGroupOlxPropertiesQuery implements PublishedGroupOlxPropertiesQueryInterface
{
    /** @var list<string> */
    private const PUBLISHER_SLUGS = [
        GroupOlxConnector::SLUG,
        'xml_export',
    ];

    /**
     * @return list<PropertyModel>
     */
    public function execute(string $tenantId): array
    {
        return PublicationModel::query()
            ->where('tenant_id', $tenantId)
            ->whereHas('targets', function ($query): void {
                $query
                    ->where('status', PublicationTargetStatus::Published)
                    ->whereHas('publisher', fn ($publisher) => $publisher->whereIn('slug', self::PUBLISHER_SLUGS));
            })
            ->with([
                'property.state',
                'property.city',
                'property.neighborhood',
                'property.images',
                'property.creator',
                'property.tenant',
            ])
            ->get()
            ->map(fn (PublicationModel $publication): ?PropertyModel => $publication->property)
            ->filter()
            ->unique(fn (PropertyModel $property): string => (string) $property->id)
            ->values()
            ->all();
    }
}
