<?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
    {
        // Events table
        if (! Schema::hasTable('events')) {
            Schema::create('events', function (Blueprint $table) {
                $table->id();
                $table->foreignId('tenant_id')->constrained()->onDelete('cascade');
                $table->json('name');
                $table->json('description')->nullable();
                $table->dateTime('date');
                $table->string('slug')->unique();
                $table->string('location')->nullable();
                $table->integer('max_participants')->nullable();
                $table->json('settings')->nullable();
                $table->unsignedBigInteger('event_type_id');
                $table->boolean('is_active')->default(true);
                $table->boolean('join_link_enabled')->default(true);
                $table->boolean('photo_upload_enabled')->default(true);
                $table->boolean('task_checklist_enabled')->default(true);
                $table->string('default_locale', 5)->default('de');
                $table->enum('status', ['draft', 'published', 'archived'])->default('draft'); // From add_status_to_events
                $table->timestamps();
                $table->index(['tenant_id', 'date', 'is_active']);
                $table->foreign('event_type_id')->references('id')->on('event_types')->onDelete('restrict');
            });
        } else {
            if (! Schema::hasColumn('events', 'status')) {
                Schema::table('events', function (Blueprint $table) {
                    $table->enum('status', ['draft', 'published', 'archived'])->default('draft')->after('is_active');
                });
            }
        }

        // Task Collections
        if (! Schema::hasTable('task_collections')) {
            Schema::create('task_collections', function (Blueprint $table) {
                $table->id();
                $table->foreignId('tenant_id')->nullable()->constrained()->nullOnDelete();
                $table->string('slug')->nullable()->unique();
                $table->json('name_translations');
                $table->json('description_translations')->nullable();
                $table->foreignId('event_type_id')->nullable()->constrained()->nullOnDelete();
                $table->boolean('is_default')->default(false);
                $table->integer('position')->default(0);
                $table->timestamps();
                $table->index(['tenant_id', 'is_default', 'position']);
            });
        }

        // Tasks table
        if (! Schema::hasTable('tasks')) {
            Schema::create('tasks', function (Blueprint $table) {
                $table->id();
                $table->foreignId('tenant_id')->nullable()->constrained()->nullOnDelete();
                $table->string('slug')->nullable()->unique();
                $table->unsignedBigInteger('emotion_id')->nullable();
                $table->unsignedBigInteger('event_type_id')->nullable();
                $table->json('title');
                $table->json('description')->nullable();
                $table->json('example_text')->nullable();
                $table->dateTime('due_date')->nullable();
                $table->boolean('is_completed')->default(false);
                $table->enum('priority', ['low', 'medium', 'high', 'urgent'])->default('medium');
                $table->unsignedBigInteger('collection_id')->nullable();
                $table->enum('difficulty', ['easy', 'medium', 'hard'])->default('easy');
                $table->integer('sort_order')->default(0);
                $table->boolean('is_active')->default(true);
                $table->softDeletes(); // From add_soft_deletes_to_tasks_table
                $table->timestamps();
                $table->index(['tenant_id', 'is_completed', 'priority']);
                $table->foreign('emotion_id')->references('id')->on('emotions')->onDelete('set null');
                $table->foreign('event_type_id')->references('id')->on('event_types')->onDelete('set null');
                $table->foreign('collection_id')->references('id')->on('task_collections')->onDelete('set null');
            });
        } else {
            if (! Schema::hasColumn('tasks', 'deleted_at')) {
                Schema::table('tasks', function (Blueprint $table) {
                    $table->softDeletes();
                });
            }
        }

        // Task Collection - Task Pivot
        if (! Schema::hasTable('task_collection_task')) {
            Schema::create('task_collection_task', function (Blueprint $table) {
                $table->foreignId('task_collection_id')->constrained()->onDelete('cascade');
                $table->foreignId('task_id')->constrained()->onDelete('cascade');
                $table->primary(['task_collection_id', 'task_id']);
                $table->integer('sort_order')->default(0);
            });
        }

        // Event - Task Collection Pivot
        if (! Schema::hasTable('event_task_collection')) {
            Schema::create('event_task_collection', function (Blueprint $table) {
                $table->id();
                $table->foreignId('event_id')->constrained('events')->onDelete('cascade');
                $table->foreignId('task_collection_id')->constrained('task_collections')->onDelete('cascade');
                $table->integer('sort_order')->default(0);
                $table->timestamps();
            });
        }

        // Event - Task Pivot
        if (! Schema::hasTable('event_task')) {
            Schema::create('event_task', function (Blueprint $table) {
                $table->id();
                $table->foreignId('event_id')->constrained()->onDelete('cascade');
                $table->foreignId('task_id')->constrained()->onDelete('cascade');
                $table->integer('sort_order')->default(0);
                $table->timestamps();
            });
        }

        // Add tenant_id to tasks and collections if missing (from add_tenant_id_to_tasks_and_collections)
        if (Schema::hasTable('tasks') && ! Schema::hasColumn('tasks', 'tenant_id')) {
            Schema::table('tasks', function (Blueprint $table) {
                $table->foreignId('tenant_id')->constrained('tenants')->onDelete('cascade')->after('id');
                $table->index('tenant_id');
            });
        }
        if (Schema::hasTable('task_collections') && ! Schema::hasColumn('task_collections', 'tenant_id')) {
            Schema::table('task_collections', function (Blueprint $table) {
                $table->foreignId('tenant_id')->constrained('tenants')->onDelete('cascade')->after('id');
                $table->index('tenant_id');
            });
        }
    }

    public function down(): void
    {
        if (app()->environment('local', 'testing')) {
            Schema::dropIfExists('event_task');
            Schema::dropIfExists('event_task_collection');
            Schema::dropIfExists('task_collection_task');
            if (Schema::hasColumn('task_collections', 'tenant_id')) {
                Schema::table('task_collections', function (Blueprint $table) {
                    $table->dropForeign(['tenant_id']);
                    $table->dropColumn('tenant_id');
                });
            }
            Schema::dropIfExists('task_collections');
            if (Schema::hasColumn('tasks', 'tenant_id')) {
                Schema::table('tasks', function (Blueprint $table) {
                    $table->dropForeign(['tenant_id']);
                    $table->dropColumn('tenant_id');
                });
            }
            if (Schema::hasColumn('tasks', 'deleted_at')) {
                Schema::table('tasks', function (Blueprint $table) {
                    $table->dropSoftDeletes();
                });
            }
            Schema::dropIfExists('tasks');
            if (Schema::hasColumn('events', 'status')) {
                Schema::table('events', function (Blueprint $table) {
                    $table->dropColumn('status');
                });
            }
            Schema::dropIfExists('events');
        }
    }
};
