<?php

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

return new class extends Migration
{
    public function up(): void
    {
        if (! Schema::hasTable('emotions') || Schema::hasColumn('emotions', 'tenant_id')) {
            return;
        }

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

        // Treat all existing emotions as global by default
        DB::table('emotions')->update(['tenant_id' => null]);
    }

    public function down(): void
    {
        if (! Schema::hasTable('emotions') || ! Schema::hasColumn('emotions', 'tenant_id')) {
            return;
        }

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