<?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
    {
        if (Schema::hasTable('tasks')) {
            Schema::table('tasks', function (Blueprint $table) {
                if (! Schema::hasColumn('tasks', 'source_task_id')) {
                    $table->foreignId('source_task_id')->nullable()->after('tenant_id')->constrained('tasks')->nullOnDelete();
                }

                if (! Schema::hasColumn('tasks', 'source_collection_id')) {
                    $table->foreignId('source_collection_id')->nullable()->after('collection_id')->constrained('task_collections')->nullOnDelete();
                }
            });
        }

        if (Schema::hasTable('task_collections') && ! Schema::hasColumn('task_collections', 'source_collection_id')) {
            Schema::table('task_collections', function (Blueprint $table) {
                $table->foreignId('source_collection_id')->nullable()->after('event_type_id')->constrained('task_collections')->nullOnDelete();
            });
        }

        if (Schema::hasTable('emotions') && ! Schema::hasColumn('emotions', 'tenant_id')) {
            Schema::table('emotions', function (Blueprint $table) {
                $table->foreignId('tenant_id')->nullable()->after('id')->constrained('tenants')->nullOnDelete();
                $table->index('tenant_id');
            });
        }
    }

    public function down(): void
    {
        if (Schema::hasTable('tasks')) {
            Schema::table('tasks', function (Blueprint $table) {
                if (Schema::hasColumn('tasks', 'source_task_id')) {
                    $table->dropForeign(['source_task_id']);
                    $table->dropColumn('source_task_id');
                }

                if (Schema::hasColumn('tasks', 'source_collection_id')) {
                    $table->dropForeign(['source_collection_id']);
                    $table->dropColumn('source_collection_id');
                }
            });
        }

        if (Schema::hasTable('task_collections') && Schema::hasColumn('task_collections', 'source_collection_id')) {
            Schema::table('task_collections', function (Blueprint $table) {
                $table->dropForeign(['source_collection_id']);
                $table->dropColumn('source_collection_id');
            });
        }

        if (Schema::hasTable('emotions') && Schema::hasColumn('emotions', 'tenant_id')) {
            Schema::table('emotions', function (Blueprint $table) {
                $table->dropForeign(['tenant_id']);
                $table->dropIndex(['tenant_id']);
                $table->dropColumn('tenant_id');
            });
        }
    }
};
