<?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::table('terminals', function (Blueprint $table) {
            $table->renameColumn('diagram_url', 'diagram_urls');
        });

        // Migrate existing string URLs to JSON array format
        DB::table('terminals')->whereNotNull('diagram_urls')->orderBy('id')->each(function ($terminal) {
            $decoded = json_decode($terminal->diagram_urls, true);
            if (is_array($decoded)) {
                return; // Already JSON, skip
            }

            DB::table('terminals')->where('id', $terminal->id)->update([
                'diagram_urls' => json_encode([['title' => '默认组态', 'url' => $terminal->diagram_urls]]),
            ]);
        });

        Schema::table('terminals', function (Blueprint $table) {
            $table->json('diagram_urls')->nullable()->comment('组态界面地址')->change();
        });
    }

    public function down(): void
    {
        // Extract first URL back to string
        DB::table('terminals')->whereNotNull('diagram_urls')->orderBy('id')->each(function ($terminal) {
            $decoded = json_decode($terminal->diagram_urls, true);
            $url = is_array($decoded) ? ($decoded[0]['url'] ?? null) : $terminal->diagram_urls;

            DB::table('terminals')->where('id', $terminal->id)->update([
                'diagram_urls' => $url,
            ]);
        });

        Schema::table('terminals', function (Blueprint $table) {
            $table->string('diagram_urls', 500)->nullable()->comment('组态界面地址')->change();
        });

        Schema::table('terminals', function (Blueprint $table) {
            $table->renameColumn('diagram_urls', 'diagram_url');
        });
    }
};
