<?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('website_type_extras', function (Blueprint $table): void {
            $table->string('codigo')->nullable()->after('website_type_code');
        });

        Schema::table('websites_extras', function (Blueprint $table): void {
            $table->unique(
                ['website_code', 'website_type_extra_id'],
                'websites_extras_website_definition_unique'
            );
        });

        DB::table('website_type_extras')
            ->select(['id', 'nombre'])
            ->orderBy('id')
            ->each(function (object $extra): void {
                DB::table('website_type_extras')
                    ->where('id', $extra->id)
                    ->update(['codigo' => $extra->nombre]);
            });

        Schema::table('website_type_extras', function (Blueprint $table): void {
            $table->string('codigo')->nullable(false)->change();
            $table->unique(
                ['website_type_code', 'codigo'],
                'website_type_extras_type_code_unique'
            );
        });
    }

    public function down(): void
    {
        Schema::table('websites_extras', function (Blueprint $table): void {
            $table->dropUnique('websites_extras_website_definition_unique');
        });

        Schema::table('website_type_extras', function (Blueprint $table): void {
            $table->dropUnique('website_type_extras_type_code_unique');
            $table->dropColumn('codigo');
        });
    }
};
