<?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 extras para transferências na tabela transactions
        Schema::table('transactions', function (Blueprint $table) {
            if (!Schema::hasColumn('transactions', 'is_transfer')) {
                $table->boolean('is_transfer')->default(false)->after('is_split_parent');
            }
            if (!Schema::hasColumn('transactions', 'transfer_linked_id')) {
                $table->unsignedBigInteger('transfer_linked_id')->nullable()->after('is_transfer');
            }
        });

        // Criar tabela para pares de transferência ignorados
        if (!Schema::hasTable('ignored_transfer_pairs')) {
            Schema::create('ignored_transfer_pairs', function (Blueprint $table) {
                $table->id();
                $table->foreignId('user_id')->constrained()->onDelete('cascade');
                $table->unsignedBigInteger('debit_transaction_id');
                $table->unsignedBigInteger('credit_transaction_id');
                $table->timestamps();
                
                $table->unique(['user_id', 'debit_transaction_id', 'credit_transaction_id'], 'unique_ignored_pair');
                $table->index('user_id');
            });
        }
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::table('transactions', function (Blueprint $table) {
            if (Schema::hasColumn('transactions', 'is_transfer')) {
                $table->dropColumn('is_transfer');
            }
            if (Schema::hasColumn('transactions', 'transfer_linked_id')) {
                $table->dropColumn('transfer_linked_id');
            }
        });

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