<?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
    {
        // Event Types
        if (!Schema::hasTable('event_types')) {
            Schema::create('event_types', function (Blueprint $table) {
                $table->id();
                $table->json('name');
                $table->string('slug')->unique();
                $table->string('icon')->nullable();
                $table->json('settings')->nullable();
                $table->timestamps();
            });
        }

        // Emotions
        if (!Schema::hasTable('emotions')) {
            Schema::create('emotions', function (Blueprint $table) {
                $table->id();
                $table->json('name');
                $table->string('icon', 50);
                $table->string('color', 7);
                $table->json('description')->nullable();
                $table->integer('sort_order')->default(0);
                $table->boolean('is_active')->default(true);
                $table->timestamps();
            });
        }

        // Pivot table for emotions and event types
        if (!Schema::hasTable('emotion_event_type')) {
            Schema::create('emotion_event_type', function (Blueprint $table) {
                $table->unsignedBigInteger('emotion_id');
                $table->unsignedBigInteger('event_type_id');
                $table->primary(['emotion_id', 'event_type_id']);
                $table->foreign('emotion_id')->references('id')->on('emotions')->onDelete('cascade');
                $table->foreign('event_type_id')->references('id')->on('event_types')->onDelete('cascade');
            });
        }
    }

    public function down(): void
    {
        if (app()->environment('local', 'testing')) {
            Schema::dropIfExists('emotion_event_type');
            Schema::dropIfExists('emotions');
            Schema::dropIfExists('event_types');
        }
    }
};