<?php

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

return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::create('credits', function (Blueprint $table) {
            $table->id();

            // CLAVES DE RELACIÓN Y MULTI-TENANT
            $table->foreignId('company_id')->constrained()->cascadeOnDelete();
            $table->foreignId('client_id')->constrained()->cascadeOnDelete();

            // Refinanciación/Reestructuración
            $table->foreignId('parent_credit_id')->nullable()->constrained('credits')->nullOnDelete()->comment('Referencia al crédito original en operaciones de refinanciación, reestructuración o extensión.');

            $table->foreignId('collector_user_id')->nullable()->constrained('users')->nullOnDelete()->comment('Cobrador asignado.');
            $table->foreignId('created_by_user_id')->constrained('users')->cascadeOnDelete()->comment('Usuario que crea el registro.');

            // DATOS FINANCIEROS
            $table->enum('status', ['delayed', 'active', 'paid', 'canceled', 'overdue'])->default('active');
            $table->decimal('amount', 10, 2)->comment('Monto principal del préstamo.');
            $table->decimal('interest_rate', 5, 2)->comment('Tasa de interés (%)');
            $table->unsignedInteger('installments_count')->comment('Número total de cuotas.');

            // DATOS DE COBRO
            $table->enum('periodicity', ['daily', 'weekly', 'biweekly', 'monthly']);
            $table->date('start_date')->comment('Fecha de desembolso.');
            $table->date('first_due_date_override')->nullable()->comment('Anulación de la fecha de la primera cuota.'); // Añadido
            $table->date('due_date')->nullable()->comment('Fecha de vencimiento del crédito.');

            // DÍAS DE COBRO
            $table->unsignedInteger('due_day_1')->nullable()->comment('Día del mes (1-31) o día de la semana (1-7)');
            $table->unsignedInteger('due_day_2')->nullable()->comment('Segundo día del mes (solo para biweekly)');

            $table->timestamps();
        });
    }

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