<?php

namespace App\Console\Commands;

use App\Models\AppearanceSetting;
use App\Support\AppearanceRegistry;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Schema;

class SyncAppearanceSettings extends Command
{
    protected $signature   = 'appearance:sync';
    protected $description = 'Upsert appearance settings from the registry into the database. Safe to run on existing installs — only inserts missing rows, never overwrites admin-set values.';

    public function handle(): int
    {
        if (! Schema::hasTable('appearance_settings')) {
            $this->error('Table appearance_settings does not exist. Run php artisan migrate first.');
            return self::FAILURE;
        }

        $definitions = AppearanceRegistry::definitions();
        $inserted    = 0;
        $skipped     = 0;

        foreach ($definitions as $key => $def) {
            $exists = AppearanceSetting::where('key', $key)
                ->where(function ($q) use ($def) {
                    if ($def['theme'] === null) {
                        $q->whereNull('theme_slug');
                    } else {
                        $q->where('theme_slug', $def['theme']);
                    }
                })
                ->exists();

            if ($exists) {
                $skipped++;
                continue;
            }

            AppearanceSetting::create([
                'theme_slug'    => $def['theme'],
                'group'         => $def['group'],
                'key'           => $key,
                'type'          => $def['type'],
                'value'         => null,
                'default_value' => is_array($def['default']) ? json_encode($def['default']) : $def['default'],
                'label'         => $def['label'],
                'options'       => $def['options'],
                'sort_order'    => $def['sort_order'],
            ]);

            $inserted++;
        }

        $this->info("Appearance settings synced: {$inserted} inserted, {$skipped} already exist.");

        return self::SUCCESS;
    }
}
