<?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('recurring_instances', function (Blueprint $table) {
            $table->id();
            $table->foreignId('user_id')->constrained()->onDelete('cascade');
            $table->foreignId('recurring_template_id')->constrained()->onDelete('cascade');
            
            // Dados da instância
            $table->unsignedInteger('occurrence_number'); // 1, 2, 3...
            $table->date('due_date'); // Data de vencimento
            $table->decimal('planned_amount', 15, 2); // Valor previsto
            
            // Status da instância
            $table->enum('status', [
                'pending',   // Aguardando pagamento
                'paid',      // Pago/Conciliado
                'skipped',   // Pulado (ex: férias)
                'cancelled'  // Cancelado
            ])->default('pending');
            
            // Conciliação com transação
            $table->foreignId('transaction_id')->nullable()->constrained()->onDelete('set null');
            $table->dateTime('paid_at')->nullable();
            $table->decimal('paid_amount', 15, 2)->nullable();
            $table->text('paid_notes')->nullable();
            
            $table->timestamps();
            $table->softDeletes();
            
            // Índices
            $table->index(['user_id', 'status'], 'ri_user_status_idx');
            $table->index(['user_id', 'due_date'], 'ri_user_due_idx');
            $table->index(['recurring_template_id', 'occurrence_number'], 'ri_template_occ_idx');
            $table->index(['recurring_template_id', 'status'], 'ri_template_status_idx');
            $table->unique(['recurring_template_id', 'occurrence_number'], 'ri_template_occ_unique');
        });

        // Adicionar campo na tabela transactions para link reverso
        Schema::table('transactions', function (Blueprint $table) {
            $table->foreignId('recurring_instance_id')
                ->nullable()
                ->after('import_log_id')
                ->constrained('recurring_instances')
                ->onDelete('set null');
        });
    }

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

        Schema::dropIfExists('recurring_instances');
    }
};
