<?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(): void
    {
        // 1. Agregar columna nullable inicialmente
        Schema::table('installments', function (Blueprint $table) {
            $table->unsignedBigInteger('company_id')->nullable()->after('id');
        });

        // 2. Migrar datos existentes: copiar company_id desde credits
        DB::statement('
            UPDATE installments i
            INNER JOIN credits c ON i.credit_id = c.id
            SET i.company_id = c.company_id
        ');

        // 3. Hacer la columna NOT NULL y agregar índices
        Schema::table('installments', function (Blueprint $table) {
            $table->unsignedBigInteger('company_id')->nullable(false)->change();

            // Índice para queries filtrados por company
            $table->index('company_id');

            // Índice compuesto para queries comunes
            $table->index(['company_id', 'status']);
            $table->index(['company_id', 'due_date']);

            // Foreign key
            $table->foreign('company_id')
                ->references('id')
                ->on('companies')
                ->onDelete('cascade');
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::table('installments', function (Blueprint $table) {
            $table->dropForeign(['company_id']);
            $table->dropIndex(['company_id', 'due_date']);
            $table->dropIndex(['company_id', 'status']);
            $table->dropIndex(['company_id']);
            $table->dropColumn('company_id');
        });
    }
};
