<?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
    {
        // Adicionar campos de reembolso na tabela transactions
        Schema::table('transactions', function (Blueprint $table) {
            $table->boolean('is_refund_pair')->default(false)->after('is_transfer');
            $table->foreignId('refund_linked_id')->nullable()->after('is_refund_pair')
                ->constrained('transactions')->onDelete('set null');
        });

        // Criar tabela para pares de reembolso ignorados
        Schema::create('ignored_refund_pairs', function (Blueprint $table) {
            $table->id();
            $table->foreignId('user_id')->constrained()->onDelete('cascade');
            $table->foreignId('debit_id')->constrained('transactions')->onDelete('cascade');
            $table->foreignId('credit_id')->constrained('transactions')->onDelete('cascade');
            $table->timestamp('created_at')->useCurrent();
            
            $table->unique(['user_id', 'debit_id', 'credit_id']);
            $table->index(['user_id']);
        });
    }

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