<?php

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

/**
 * Matching engine configuration + an audit log of every match run.
 *
 * bms_matching_settings holds the admin-tunable weights + threshold (one row
 * per business). bms_match_runs logs each scored run (client or employee)
 * against the lead for sales context, including the input criteria and the
 * ranked results with reasons-for-exclusion.
 */
return new class extends Migration {
    public function up(): void
    {
        if (! Schema::hasTable('bms_matching_settings')) {
            Schema::create('bms_matching_settings', function (Blueprint $t) {
                $t->bigIncrements('id');
                $t->unsignedInteger('business_id');
                $t->unsignedTinyInteger('threshold')->default(60);
                $t->json('weights')->nullable();             // criterion => weight
                $t->unsignedInteger('updated_by')->nullable();
                $t->timestamps();
                $t->unique('business_id');
            });
        }

        if (! Schema::hasTable('bms_match_runs')) {
            Schema::create('bms_match_runs', function (Blueprint $t) {
                $t->bigIncrements('id');
                $t->unsignedInteger('business_id');
                $t->enum('source', ['client', 'employee'])->default('client');
                $t->unsignedBigInteger('wizard_session_id')->nullable();
                $t->unsignedBigInteger('lead_id')->nullable();
                $t->json('criteria')->nullable();            // wizard inputs that drove the run
                $t->json('results')->nullable();             // [{hall_id, score, matched, reasons[]}]
                $t->unsignedTinyInteger('top_score')->nullable();
                $t->unsignedInteger('matched_count')->default(0);
                $t->unsignedInteger('created_by')->nullable();
                $t->timestamps();
                $t->index(['business_id', 'lead_id']);
                $t->index(['business_id', 'wizard_session_id']);
            });
        }
    }

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