<?php

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

/**
 * Migrate the legacy `Settings::site.logo_path` into the active theme's
 * `assets.logo_light`. Theme assets are now the single source of truth
 * for the brand logo; the Settings page logo upload is being retired.
 *
 * If both the active theme already has a `logo_light` AND a legacy logo
 * path exists, the theme's value wins — admins who already moved to the
 * appearance editor don't get clobbered. The legacy path is then cleared
 * either way so the Settings row doesn't linger after the UI is removed.
 */
return new class extends Migration
{
    public function up(): void
    {
        $row = DB::table('settings')
            ->where('key', 'site.logo_path')
            ->first(['value']);

        if (! $row) {
            return;
        }

        // Settings.value is JSON-cast; the raw column holds e.g. `"branding/logo-…"`.
        $legacyPath = json_decode((string) $row->value, true);
        $legacyPath = is_string($legacyPath) ? $legacyPath : null;

        if (is_string($legacyPath) && $legacyPath !== '') {
            $active = DB::table('theme_versions')->where('is_active', true)->first();
            if ($active) {
                $assets = is_string($active->assets) ? (json_decode($active->assets, true) ?? []) : [];
                if (! is_array($assets)) {
                    $assets = [];
                }
                if (empty($assets['logo_light'])) {
                    $assets['logo_light'] = $legacyPath;
                    DB::table('theme_versions')
                        ->where('id', $active->id)
                        ->update([
                            'assets' => json_encode($assets),
                            'derived' => null,  // force re-derive on next read
                            'updated_at' => now(),
                        ]);
                }
            }
        }

        // Clear the legacy row so the obsolete UI's absence doesn't leave
        // an orphan setting around. The blob on disk is preserved — the
        // theme row now points at the same path.
        DB::table('settings')->where('key', 'site.logo_path')->delete();
    }

    public function down(): void
    {
        // No-op: this migration is one-way. Re-introducing the legacy
        // setting from theme assets would conflict with admins who set
        // a different logo in the theme editor after the migration ran.
    }
};
