<?php

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

/**
 * Let `navbar_style` hold 'glass'.
 *
 * The frosted navbar template exists and the dispatcher accepts it, but the
 * CHECK constraint predates it — so choosing it in the theme editor failed at
 * write time with a constraint violation rather than a validation message.
 *
 * The three legacy values with no template of their own — hamburger_always,
 * side_drawer, mega — are deliberately kept. Any of them already stored would
 * make this migration fail if dropped, and the navbar dispatcher already falls
 * back to 'solid' for a style it cannot resolve, so they are inert rather than
 * broken.
 */
return new class extends Migration
{
    private const STYLES = [
        'solid', 'transparent', 'glass', 'floating', 'centered', 'minimal',
        // Legacy, no template — the dispatcher renders these as 'solid'.
        'hamburger_always', 'side_drawer', 'mega',
    ];

    public function up(): void
    {
        if (! Schema::hasTable('website_settings') || ! Schema::hasColumn('website_settings', 'navbar_style')) {
            return;
        }

        $list = collect(self::STYLES)->map(fn ($s) => "'".$s."'")->implode(', ');

        DB::statement('ALTER TABLE website_settings DROP CONSTRAINT IF EXISTS website_settings_navbar_style_check');
        DB::statement("ALTER TABLE website_settings ADD CONSTRAINT website_settings_navbar_style_check CHECK (navbar_style IN ({$list}))");
    }

    public function down(): void
    {
        if (! Schema::hasTable('website_settings') || ! Schema::hasColumn('website_settings', 'navbar_style')) {
            return;
        }

        // Anything left on the value this migration introduced would violate the
        // restored constraint, so move it to the nearest style that still exists.
        DB::table('website_settings')->where('navbar_style', 'glass')->update(['navbar_style' => 'transparent']);

        DB::statement('ALTER TABLE website_settings DROP CONSTRAINT IF EXISTS website_settings_navbar_style_check');
        DB::statement("ALTER TABLE website_settings ADD CONSTRAINT website_settings_navbar_style_check CHECK (navbar_style IN ('solid', 'transparent', 'floating', 'centered', 'hamburger_always', 'side_drawer', 'minimal', 'mega'))");
    }
};
