<?php

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

class CreateEmailLeadLinksTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('email_lead_links', function (Blueprint $table) {
            $table->id();
            $table->unsignedBigInteger('email_id')->comment('Foreign key to emails table');
            $table->unsignedBigInteger('lead_id')->comment('Foreign key to crm_lead_data table');
            $table->unsignedBigInteger('lender_id')->nullable()->comment('Foreign key to crm_lender table');
            $table->string('company_name')->nullable()->comment('Company name extracted from email subject');
            $table->string('matched_email')->nullable()->comment('The email that matched from lender');
            $table->timestamp('processed_at')->useCurrent()->comment('When this link was created');

            // Indexes for faster lookups
            $table->index('email_id');
            $table->index('lead_id');
            $table->index('lender_id');
            $table->index('processed_at');

            // Prevent duplicate links
            $table->unique(['email_id', 'lead_id'], 'unique_email_lead');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('email_lead_links');
    }
}
