<?php

declare(strict_types=1);

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\File;

class ThemesPublishCommand extends Command
{
    protected $signature = 'themes:publish {theme? : Theme slug to publish; omit for all}';

    protected $description = 'Copy theme assets into public/themes for correct static MIME serving';

    public function handle(): int
    {
        $themePath = config('larablog.theme_path', base_path('themes'));
        $publicBase = public_path('themes');
        File::ensureDirectoryExists($publicBase);

        $only = $this->argument('theme');
        $directories = collect(File::directories($themePath))
            ->when($only, fn ($c) => $c->filter(fn ($dir) => basename($dir) === $only));

        if ($directories->isEmpty()) {
            $this->error($only ? "Theme [{$only}] not found." : 'No themes found.');

            return self::FAILURE;
        }

        foreach ($directories as $directory) {
            $slug = basename($directory);
            $assets = $directory.'/assets';
            if (! is_dir($assets)) {
                $this->warn("Skip {$slug}: no assets/");

                continue;
            }

            $target = $publicBase.'/'.$slug;
            File::deleteDirectory($target);
            File::copyDirectory($assets, $target);
            $this->info("Published theme assets: {$slug} → public/themes/{$slug}");
        }

        return self::SUCCESS;
    }
}
