<?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
    {
        foreach (['play_types', 'play_config_items'] as $table) {
            Schema::table($table, function (Blueprint $blueprint): void {
                $blueprint->string('display_name', 64)->nullable()->after('bet_mode');
            });

            DB::table($table)->update([
                'display_name' => DB::raw(
                    "COALESCE(
                        NULLIF(TRIM(display_name_zh), ''),
                        NULLIF(TRIM(display_name_en), ''),
                        NULLIF(TRIM(display_name_ne), ''),
                        play_code
                    )",
                ),
            ]);

            Schema::table($table, function (Blueprint $blueprint): void {
                $blueprint->dropColumn(['display_name_zh', 'display_name_en', 'display_name_ne']);
            });
        }
    }

    public function down(): void
    {
        foreach (['play_types', 'play_config_items'] as $table) {
            Schema::table($table, function (Blueprint $blueprint): void {
                $blueprint->string('display_name_zh', 64)->nullable()->after('bet_mode');
                $blueprint->string('display_name_en', 64)->nullable()->after('display_name_zh');
                $blueprint->string('display_name_ne', 64)->nullable()->after('display_name_en');
            });

            DB::table($table)->update([
                'display_name_zh' => DB::raw('display_name'),
                'display_name_en' => DB::raw('display_name'),
                'display_name_ne' => DB::raw('display_name'),
            ]);

            Schema::table($table, function (Blueprint $blueprint): void {
                $blueprint->dropColumn('display_name');
            });
        }
    }
};
