<?php

declare(strict_types=1);

namespace App\Console\Commands;

use App\Models\WorldWebStory;
use App\Services\WebStories\WorldWebStoryAssetService;
use Illuminate\Console\Command;

final class BuildWorldWebStoryAssetsCommand extends Command
{
    protected $signature = 'skinbase:webstories:build-assets
        {story? : Story ID or slug}
        {--published : Limit batch mode to published stories}
        {--visible : Limit batch mode to stories currently visible on the public site}
        {--limit=100 : Maximum stories to process in batch mode}
        {--force : Rebuild already populated asset paths}
        {--dry-run : Report changes without saving them}';

    protected $description = 'Backfill poster, logo, and page background assets for World Web Stories';

    public function handle(WorldWebStoryAssetService $assets): int
    {
        $storyKey = $this->argument('story');
        $force = (bool) $this->option('force');
        $dryRun = (bool) $this->option('dry-run');

        if ($storyKey !== null && trim((string) $storyKey) !== '') {
            $story = $this->resolveStory((string) $storyKey);

            if (! $story instanceof WorldWebStory) {
                $this->error(sprintf('Web story [%s] was not found.', (string) $storyKey));

                return self::FAILURE;
            }

            return $this->buildOne($assets, $story, $force, $dryRun);
        }

        return $this->buildBatch($assets, $force, $dryRun, max(1, (int) $this->option('limit')));
    }

    private function buildOne(WorldWebStoryAssetService $assets, WorldWebStory $story, bool $force, bool $dryRun): int
    {
        $result = $assets->buildAssets($story, force: $force, dryRun: $dryRun);

        $this->line(sprintf('Story [%d] %s', (int) $story->id, (string) $story->slug));
        $this->line($result['updated'] ? 'Assets updated.' : 'No asset changes needed.');

        foreach ((array) $result['story'] as $field => $value) {
            $this->line(sprintf(' - story.%s = %s', (string) $field, (string) $value));
        }

        foreach ((array) $result['pages'] as $pageId => $changes) {
            foreach ((array) $changes as $field => $value) {
                $this->line(sprintf(' - page.%d.%s = %s', (int) $pageId, (string) $field, (string) $value));
            }
        }

        return self::SUCCESS;
    }

    private function buildBatch(WorldWebStoryAssetService $assets, bool $force, bool $dryRun, int $limit): int
    {
        $processed = 0;
        $updated = 0;

        $this->storyQuery()
            ->limit($limit)
            ->get()
            ->each(function (WorldWebStory $story) use ($assets, $force, $dryRun, &$processed, &$updated): void {
                $processed++;
                $result = $assets->buildAssets($story, force: $force, dryRun: $dryRun);

                if ($result['updated']) {
                    $updated++;
                }

                $this->line(sprintf('[%d] %s -> %s', (int) $story->id, (string) $story->slug, $result['updated'] ? 'updated' : 'unchanged'));
            });

        $this->info(sprintf('Done. processed=%d updated=%d', $processed, $updated));

        return self::SUCCESS;
    }

    private function storyQuery()
    {
        return WorldWebStory::query()
            ->when((bool) $this->option('published'), fn ($query) => $query->published())
            ->when((bool) $this->option('visible'), fn ($query) => $query->visible())
            ->orderByDesc('published_at')
            ->orderByDesc('id');
    }

    private function resolveStory(string $value): ?WorldWebStory
    {
        return WorldWebStory::query()
            ->when(is_numeric($value), fn ($query) => $query->where('id', (int) $value), fn ($query) => $query->where('slug', $value))
            ->first();
    }
}