<?php

namespace Mtc\Modules\BlockRegistry\Console\Commands;

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

class BlocksImportCommand extends Command
{
    protected $signature = 'blocks:import {slug? : Import a specific block by slug} {--all : Import all blocks} {--force : Skip confirmation prompt}';
    protected $description = 'Import block definitions from JSON files into the database';

    public function handle(BlockSyncService $syncService): int
    {
        $slug = $this->argument('slug');

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

        // Default to importing all if no slug given
        return $this->importAll($syncService);
    }

    protected function importSingle(BlockSyncService $syncService, string $slug): int
    {
        $dir = $syncService->getBlocksDirectory();
        $filePath = $dir . '/' . $slug . '.json';

        if (!file_exists($filePath)) {
            $this->error("JSON file not found: {$filePath}");
            return 1;
        }

        if (!$this->option('force') && !$this->confirm("Import block '{$slug}' from JSON? This will overwrite the current DB definition.")) {
            $this->info('Cancelled.');
            return 0;
        }

        try {
            $data = $syncService->readBlockFile($filePath);
            $syncService->importBlock($data);
            $this->info("Imported '{$slug}' successfully.");
            return 0;
        } catch (\Exception $e) {
            $this->error("Failed to import '{$slug}': " . $e->getMessage());
            return 1;
        }
    }

    protected function importAll(BlockSyncService $syncService): int
    {
        $dir = $syncService->getBlocksDirectory();

        if (!is_dir($dir)) {
            $this->warn("No blocks directory found at {$dir}");
            return 0;
        }

        $files = glob($dir . '/*.json');
        if (empty($files)) {
            $this->warn('No JSON files found in ' . $dir);
            return 0;
        }

        if (!$this->option('force') && !$this->confirm('Import ' . count($files) . ' block(s) from JSON? This will overwrite current DB definitions.')) {
            $this->info('Cancelled.');
            return 0;
        }

        $result = $syncService->importAllBlocks();

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

        if (!empty($result['updated'])) {
            $this->info('Updated ' . count($result['updated']) . ' block(s):');
            foreach ($result['updated'] 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;
        }

        $total = count($result['created']) + count($result['updated']);
        $this->newLine();
        $this->info("Done. {$total} block(s) synced.");

        return 0;
    }
}
