<?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
    {
        Schema::table('campaigns', function (Blueprint $table) {
            $table->foreignId('user_id')->nullable()->after('created_by')->constrained()->cascadeOnDelete();
        });

        // Backfill from the existing (unconstrained) created_by column so
        // pre-existing campaigns keep their owner under the new tenant FK.
        DB::table('campaigns')->update(['user_id' => DB::raw('created_by')]);

        Schema::table('campaigns', function (Blueprint $table) {
            $table->dropUnique(['slug']);
            $table->unique(['user_id', 'slug']);
        });
    }

    public function down(): void
    {
        Schema::table('campaigns', function (Blueprint $table) {
            $table->dropUnique(['user_id', 'slug']);
            $table->unique('slug');
        });

        Schema::table('campaigns', function (Blueprint $table) {
            $table->dropConstrainedForeignId('user_id');
        });
    }
};
