<?php

declare(strict_types=1);

namespace ImovelZapAi\Publishing\Application\Queries;

use ImovelZapAi\Properties\Infrastructure\Persistence\Eloquent\PropertyModel;
use ImovelZapAi\Publishing\Domain\Enums\PublicationTargetStatus;
use ImovelZapAi\Publishing\Infrastructure\Persistence\Eloquent\PublicationModel;

final class PublishedFeedPropertiesQuery
{
    /**
     * @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->where('slug', 'xml_export'));
            })
            ->with([
                'property.state',
                'property.city',
                'property.neighborhood',
                'property.images',
                'property.creator',
                'property.tenant',
            ])
            ->get()
            ->map(fn (PublicationModel $publication): ?PropertyModel => $publication->property)
            ->filter()
            ->values()
            ->all();
    }
}
