<?php

declare(strict_types=1);

namespace ImovelZapAi\Publishing\Application\Actions;

use App\Models\User;
use ImovelZapAi\Properties\Infrastructure\Persistence\Eloquent\PropertyModel;
use ImovelZapAi\Publishing\Domain\Enums\PublicationTargetStatus;
use ImovelZapAi\Publishing\Infrastructure\Persistence\Eloquent\PublicationModel;
use ImovelZapAi\Publishing\Infrastructure\Persistence\Eloquent\PublicationTargetModel;

final class SyncPropertyPublicationsAction
{
    public function __construct(
        private readonly QueuePropertyPublicationAction $queuePublication,
    ) {}

    /**
     * @return list<PublicationTargetModel>
     */
    public function execute(PropertyModel $property, ?User $actor = null): array
    {
        /** @var PublicationModel|null $publication */
        $publication = PublicationModel::query()
            ->where('tenant_id', $property->tenant_id)
            ->where('property_id', $property->id)
            ->with(['targets.publisher'])
            ->first();

        if ($publication === null) {
            return [];
        }

        $queued = [];

        foreach ($publication->targets as $target) {
            if (! in_array($target->status, [
                PublicationTargetStatus::Published,
                PublicationTargetStatus::Failed,
            ], true)) {
                continue;
            }

            if ($target->publisher === null) {
                continue;
            }

            $queued[] = $this->queuePublication->execute(
                property: $property,
                publisher: $target->publisher,
                actor: $actor,
                isUpdate: true,
            );
        }

        return $queued;
    }
}
