<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    public function up(): void
    {
        Schema::create('appearance_settings', function (Blueprint $table) {
            $table->id();
            $table->string('theme_slug', 50)->nullable()->index();
            $table->string('group', 50);
            $table->string('key', 100);
            $table->string('type', 20);
            $table->text('value')->nullable();
            $table->text('default_value')->nullable();
            $table->string('label', 150);
            $table->json('options')->nullable();
            $table->unsignedInteger('sort_order')->default(0);
            $table->timestamps();

            $table->unique(['theme_slug', 'key']);
        });

        // Seed all registry definitions so the table is usable immediately
        // after migrate without requiring a separate artisan appearance:sync step.
        $now  = now();
        $rows = [];

        foreach (\App\Support\AppearanceRegistry::definitions() as $key => $def) {
            $rows[] = [
                'theme_slug'    => $def['theme'],
                'group'         => $def['group'],
                'key'           => $key,
                'type'          => $def['type'],
                'value'         => null,
                'default_value' => $def['default'],
                'label'         => $def['label'],
                'options'       => isset($def['options']) ? json_encode($def['options']) : null,
                'sort_order'    => $def['sort_order'],
                'created_at'    => $now,
                'updated_at'    => $now,
            ];
        }

        DB::table('appearance_settings')->insert($rows);
    }

    public function down(): void
    {
        Schema::dropIfExists('appearance_settings');
    }
};
