<?php

declare(strict_types=1);

namespace ImovelZapAi\Publishing\Infrastructure\Connectors;

use ImovelZapAi\Properties\Application\Services\PropertyListingUrlResolver;
use ImovelZapAi\Publishing\Application\Data\PublicationContextData;
use ImovelZapAi\Publishing\Application\Data\PublicationOperationResultData;
use ImovelZapAi\Publishing\Application\Data\PublicationStatusResultData;
use ImovelZapAi\Publishing\Application\Ports\PublisherInterface;
use ImovelZapAi\Publishing\Domain\Enums\PublicationTargetStatus;

final class ExternalLinkPublisher implements PublisherInterface
{
    public function __construct(
        private readonly PropertyListingUrlResolver $listingUrlResolver,
    ) {}

    public function slug(): string
    {
        return 'external_link';
    }

    public function publish(PublicationContextData $context): PublicationOperationResultData
    {
        return $this->syncLink($context, 'Link externo publicado.');
    }

    public function update(PublicationContextData $context): PublicationOperationResultData
    {
        return $this->syncLink($context, 'Link externo atualizado.');
    }

    public function remove(PublicationContextData $context): PublicationOperationResultData
    {
        return PublicationOperationResultData::succeeded(
            externalId: $context->target?->external_id ?? $context->property->internal_code,
            message: 'Link externo removido.',
        );
    }

    public function status(PublicationContextData $context): PublicationStatusResultData
    {
        if ($context->target?->status === PublicationTargetStatus::Removed) {
            return new PublicationStatusResultData(
                status: PublicationTargetStatus::Removed,
                isPublished: false,
                externalId: $context->target->external_id,
                message: 'Link externo removido.',
            );
        }

        $url = $this->listingUrlResolver->resolve($context->property);

        return new PublicationStatusResultData(
            status: PublicationTargetStatus::Published,
            isPublished: true,
            externalId: $context->property->internal_code,
            externalUrl: $url,
            message: 'Link externo ativo.',
        );
    }

    private function syncLink(
        PublicationContextData $context,
        string $successMessage,
    ): PublicationOperationResultData {
        $url = $this->listingUrlResolver->resolve($context->property);

        return PublicationOperationResultData::succeeded(
            externalId: $context->property->internal_code,
            externalUrl: $url,
            message: $successMessage,
        );
    }
}
