<?php

declare(strict_types=1);

namespace App\Console\Commands;

use App\Jobs\Sitemaps\PublishSitemapReleaseJob;
use App\Services\Sitemaps\SitemapPublishService;
use Illuminate\Console\Command;

final class PublishSitemapsCommand extends Command
{
    protected $signature = 'skinbase:sitemaps:publish
        {--release= : Publish an existing built release}
        {--queue : Dispatch publish flow to the queue}
        {--sync : Run publish synchronously (default)}';

    protected $description = 'Build, validate, and atomically publish a sitemap release.';

    public function handle(SitemapPublishService $publish): int
    {
        $releaseId = $this->option('release');

        if ((bool) $this->option('queue')) {
            PublishSitemapReleaseJob::dispatch(is_string($releaseId) && $releaseId !== '' ? $releaseId : null);
            $this->info('Queued sitemap publish flow' . (is_string($releaseId) && $releaseId !== '' ? ' for release [' . $releaseId . '].' : '.'));

            return self::SUCCESS;
        }

        try {
            $manifest = $publish->publish(is_string($releaseId) && $releaseId !== '' ? $releaseId : null);
        } catch (\Throwable $exception) {
            $this->error($exception->getMessage());

            return self::FAILURE;
        }

        $this->info(sprintf(
            'Published sitemap release [%s] with %d families and %d documents.',
            (string) $manifest['release_id'],
            (int) data_get($manifest, 'totals.families', 0),
            (int) data_get($manifest, 'totals.documents', 0),
        ));

        return self::SUCCESS;
    }
}