<?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::create('deal_contact', function (Blueprint $table) {
            $table->id();
            $table->foreignId('deal_id')->constrained()->cascadeOnDelete();
            $table->foreignId('contact_id')->constrained()->cascadeOnDelete();
            $table->boolean('is_primary')->default(false);
            $table->timestamps();
            $table->unique(['deal_id', 'contact_id']);
        });

        DB::table('deals')->whereNotNull('contact_id')->orderBy('id')->each(function ($deal) {
            DB::table('deal_contact')->insertOrIgnore([
                'deal_id' => $deal->id,
                'contact_id' => $deal->contact_id,
                'is_primary' => true,
                'created_at' => now(),
                'updated_at' => now(),
            ]);
        });
    }

    public function down(): void
    {
        Schema::dropIfExists('deal_contact');
    }
};
