<?php

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

return new class extends Migration
{
    public function up(): void
    {
        Schema::table('packages', function (Blueprint $table) {
            if (! Schema::hasColumn('packages', 'name_translations')) {
                $table->json('name_translations')->nullable()->after('name');
            }

            if (! Schema::hasColumn('packages', 'description_translations')) {
                $table->json('description_translations')->nullable()->after('description');
            }
        });

        // Bootstrap existing values into the new translation columns
        if (Schema::hasColumn('packages', 'name')) {
            DB::table('packages')->select('id', 'name', 'description')->get()->each(function ($package) {
                $nameTranslations = [
                    'de' => $package->name,
                    'en' => $package->name,
                ];

                $descriptionTranslations = [
                    'de' => $package->description ?? '',
                    'en' => $package->description ?? '',
                ];

                DB::table('packages')
                    ->where('id', $package->id)
                    ->update([
                        'name_translations' => json_encode($nameTranslations, JSON_UNESCAPED_UNICODE),
                        'description_translations' => json_encode($descriptionTranslations, JSON_UNESCAPED_UNICODE),
                    ]);
            });
        }
    }

    public function down(): void
    {
        Schema::table('packages', function (Blueprint $table) {
            if (Schema::hasColumn('packages', 'name_translations')) {
                $table->dropColumn('name_translations');
            }

            if (Schema::hasColumn('packages', 'description_translations')) {
                $table->dropColumn('description_translations');
            }
        });
    }
};
