<?php

namespace Mtc\Modules\BlockRegistry\Console\Commands;

use Illuminate\Console\Command;
use Mtc\Modules\BlockRegistry\Models\BlockRegistry;
use Mtc\Modules\BlockRegistry\Services\BlockSyncService;

class BlocksExportCommand extends Command
{
    protected $signature = 'blocks:export {slug? : Export a specific block by slug} {--all : Export all blocks}';
    protected $description = 'Export block definitions from database to JSON files';

    public function handle(BlockSyncService $syncService): int
    {
        if (app()->environment('production')) {
            $this->error('Export is not allowed in production. Export from local or staging instead.');
            return 1;
        }

        $slug = $this->argument('slug');

        if ($slug) {
            return $this->exportSingle($syncService, $slug);
        }

        if ($this->option('all')) {
            return $this->exportAll($syncService);
        }

        // No args: list blocks and let user choose
        $blocks = BlockRegistry::orderBy('name')->pluck('name', 'slug')->toArray();

        if (empty($blocks)) {
            $this->warn('No blocks found in the database.');
            return 0;
        }

        $this->info('Available blocks:');
        foreach ($blocks as $blockSlug => $name) {
            $this->line("  {$blockSlug} — {$name}");
        }
        $this->newLine();
        $this->info('Usage: php artisan blocks:export <slug> or php artisan blocks:export --all');

        return 0;
    }

    protected function exportSingle(BlockSyncService $syncService, string $slug): int
    {
        $block = BlockRegistry::where('slug', $slug)->first();

        if (!$block) {
            $this->error("Block not found: {$slug}");
            return 1;
        }

        $path = $syncService->exportBlock($block);
        $this->info("Exported '{$block->name}' to {$path}");

        return 0;
    }

    protected function exportAll(BlockSyncService $syncService): int
    {
        $result = $syncService->exportAllBlocks();

        if (!empty($result['exported'])) {
            $this->info('Exported ' . count($result['exported']) . ' block(s):');
            foreach ($result['exported'] as $slug) {
                $this->line("  {$slug}");
            }
        }

        if (!empty($result['errors'])) {
            $this->newLine();
            $this->error('Errors:');
            foreach ($result['errors'] as $error) {
                $this->line("  {$error['slug']}: {$error['error']}");
            }
            return 1;
        }

        return 0;
    }
}
