<?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
{
    /**
     * Run the migrations.
     */
    public function up()
    {
        Schema::table('waiting_list', function (Blueprint $table) {
            $table->foreignId('tenant_id')->nullable()->after('id')->constrained()->cascadeOnDelete();
        });

        // Popula dados existentes baseado na fila
        DB::statement("
            UPDATE waiting_list wl
            JOIN queues q ON wl.queue_id = q.id
            SET wl.tenant_id = q.tenant_id
        ");
    }

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