<?php

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

return new class extends Migration
{
    public function up(): void
    {
        Schema::create('website_type', function (Blueprint $table): void {
            $table->id();
            $table->string('codigo')->unique();
            $table->string('nombre');
            $table->timestamps();
        });

        Schema::table('tenants', function (Blueprint $table): void {
            $table->string('website_type_code')->nullable();

            $table->foreign('website_type_code')
                ->references('codigo')
                ->on('website_type')
                ->cascadeOnUpdate()
                ->nullOnDelete();
        });

        Schema::create('website_type_extras', function (Blueprint $table): void {
            $table->id();
            $table->string('website_type_code');
            $table->foreign('website_type_code')
                ->references('codigo')
                ->on('website_type')
                ->cascadeOnUpdate()
                ->cascadeOnDelete();
            $table->string('nombre');
            $table->text('descripcion');
            $table->boolean('is_required')->default(false);
            $table->json('config_schema');
            $table->timestamps();
        });

        Schema::create('websites_extras', function (Blueprint $table): void {
            $table->id();
            $table->string('website_code');
            $table->foreignId('website_type_extra_id')
                ->constrained('website_type_extras')
                ->cascadeOnUpdate()
                ->cascadeOnDelete();
            $table->json('config');
            $table->timestamps();

            $table->foreign('website_code')
                ->references('codigo')
                ->on('tenants')
                ->cascadeOnUpdate()
                ->cascadeOnDelete();
        });
    }

    public function down(): void
    {
        Schema::dropIfExists('websites_extras');
        Schema::dropIfExists('website_type_extras');

        Schema::table('tenants', function (Blueprint $table): void {
            $table->dropForeign(['website_type_code']);
            $table->dropColumn('website_type_code');
        });

        Schema::dropIfExists('website_type');
    }
};
