<?php

namespace App\Console\Commands;

use App\Domain\Shared\Models\Academy;
use App\Domain\Website\Services\WebsiteBlueprintService;
use App\Models\User;
use Illuminate\Console\Command;

/**
 * Export or import a whole website design as JSON.
 *
 * Deliberately an explicit command, never part of db:seed — every tenant boots
 * from the same image and runs seeders on start, so an automatic import would
 * push one client's site into every other client's instance.
 */
class WebsiteBlueprintCommand extends Command
{
    protected $signature = 'website:blueprint
        {action : export|import}
        {--file= : Path to the blueprint JSON}
        {--academy= : Academy id (defaults to the first academy)}
        {--replace : Overwrite pages whose slug already exists}';

    protected $description = 'Export or import a website design (pages + blocks) as a JSON blueprint';

    public function handle(WebsiteBlueprintService $service): int
    {
        $academy = $this->option('academy')
            ? Academy::find($this->option('academy'))
            : Academy::first();

        if (! $academy) {
            $this->error('No academy found.');

            return self::FAILURE;
        }

        app()->instance('current_academy', $academy);
        $this->line("Academy: <info>{$academy->id}</info> — ".($academy->name_ar ?? $academy->name ?? ''));

        return match ($this->argument('action')) {
            'export' => $this->export($service),
            'import' => $this->import($service),
            default => tap(self::FAILURE, fn () => $this->error('Action must be export or import.')),
        };
    }

    private function export(WebsiteBlueprintService $service): int
    {
        $file = $this->option('file') ?: storage_path('app/website-blueprint.json');
        $blueprint = $service->export();

        @mkdir(dirname($file), 0775, true);
        file_put_contents(
            $file,
            json_encode($blueprint, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES),
        );

        $this->info(sprintf('Exported %d page(s) to %s', count($blueprint['pages']), $file));

        return self::SUCCESS;
    }

    private function import(WebsiteBlueprintService $service): int
    {
        $file = $this->option('file');

        if (! $file || ! is_file($file)) {
            $this->error('Provide an existing --file to import.');

            return self::FAILURE;
        }

        $blueprint = json_decode((string) file_get_contents($file), true);

        if (! is_array($blueprint)) {
            $this->error('Blueprint is not valid JSON.');

            return self::FAILURE;
        }

        $actor = User::query()->orderBy('id')->first();

        if (! $actor) {
            $this->error('No user available to attribute the import to.');

            return self::FAILURE;
        }

        if (! $this->option('replace') && ! $this->confirm('Import without replacing existing pages of the same slug?', true)) {
            return self::SUCCESS;
        }

        $stats = $service->import($blueprint, $actor, (bool) $this->option('replace'));

        $this->info("Imported {$stats['pages']} page(s), {$stats['blocks']} block(s), {$stats['menus']} menu item(s).");

        $this->line($stats['settings']
            ? '<info>Theme settings applied.</info>'
            : '<comment>No theme settings in this blueprint.</comment>');

        if ($stats['skipped']) {
            $this->warn('Skipped: '.implode(', ', array_unique($stats['skipped'])));
        }

        return self::SUCCESS;
    }
}
