<?php

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

// ══════════════════════════════════════════════════════════════════
//  InPractice — Make freelance_brief_id nullable on freelance_matches
//
//  Fixes CRIT-03: The "Browse & Send" path (primary user flow) creates
//  a match directly from a profile with no brief involved.
//  FreelanceService::sendInterest() inserts freelance_brief_id = null
//  but the original migration defined the column as NOT nullable,
//  causing an integrity constraint violation on every direct interest.
//
//  The FK constraint is also updated from cascadeOnDelete to
//  nullOnDelete — correct behaviour when a brief is deleted:
//  the match record should survive with brief_id set to null,
//  not be silently deleted along with the brief.
// ══════════════════════════════════════════════════════════════════

return new class extends Migration
{
    public function up(): void
    {
        Schema::table('freelance_matches', function (Blueprint $table) {
            // Drop the existing FK constraint before modifying the column
            $table->dropForeign(['freelance_brief_id']);

            // Re-add as nullable with nullOnDelete
            $table->foreignId('freelance_brief_id')
                  ->nullable()
                  ->change();

            $table->foreign('freelance_brief_id')
                  ->references('id')
                  ->on('freelance_briefs')
                  ->nullOnDelete();
        });
    }

    public function down(): void
    {
        Schema::table('freelance_matches', function (Blueprint $table) {
            $table->dropForeign(['freelance_brief_id']);

            $table->foreignId('freelance_brief_id')
                  ->nullable(false)
                  ->change();

            $table->foreign('freelance_brief_id')
                  ->references('id')
                  ->on('freelance_briefs')
                  ->cascadeOnDelete();
        });
    }
};
