<?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('events', function (Blueprint $table): void {
            $table->id();
            $table->string('tenant_code');
            $table->string('name');
            $table->string('address');

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

        Schema::create('event_dates', function (Blueprint $table): void {
            $table->id();
            $table->foreignId('event_id')->constrained('events')->cascadeOnDelete();
            $table->date('date');
            $table->time('time_start');
            $table->time('time_end');
        });

        Schema::table('tenants', function (Blueprint $table): void {
            $table->foreignId('active_event_id')
                ->nullable()
                ->constrained('events')
                ->nullOnDelete();
        });

        Schema::table('catalog_items', function (Blueprint $table): void {
            $table->foreignId('event_id')
                ->nullable()
                ->after('tenant_code')
                ->constrained('events')
                ->nullOnDelete();
        });

        Schema::table('variantes', function (Blueprint $table): void {
            $table->foreignId('event_date_id')
                ->nullable()
                ->after('catalog_item_id')
                ->constrained('event_dates')
                ->nullOnDelete();
            $table->unique(['catalog_item_id', 'event_date_id']);
        });
    }

    public function down(): void
    {
        Schema::table('tenants', function (Blueprint $table): void {
            $table->dropConstrainedForeignId('active_event_id');
        });

        Schema::table('variantes', function (Blueprint $table): void {
            $table->dropUnique(['catalog_item_id', 'event_date_id']);
            $table->dropConstrainedForeignId('event_date_id');
        });

        Schema::table('catalog_items', function (Blueprint $table): void {
            $table->dropConstrainedForeignId('event_id');
        });

        Schema::dropIfExists('event_dates');
        Schema::dropIfExists('events');
    }
};
