<?php

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

return new class extends Migration
{
    public function up(): void
    {
        Schema::create('payment_transfers', function (Blueprint $table) {
            $table->id();
            $table->foreignId('payment_id')->constrained('payments')->onDelete('cascade');
            $table->foreignId('provider_id')->constrained('providers')->onDelete('cascade');

            $table->string('gateway_provider')->default('pagarme');
            $table->string('gateway_entity_reference')->nullable();
            $table->string('gateway_entity_label')->nullable();
            $table->string('gateway_operation_reference')->nullable();
            $table->string('gateway_operation_label')->nullable();
            $table->string('gateway_parent_reference')->nullable();
            $table->string('gateway_parent_label')->nullable();
            $table->string('gateway_transfer_target_reference')->nullable();
            $table->string('gateway_transfer_target_label')->nullable();

            $table->enum('status', ['pending', 'processing', 'transferred', 'failed', 'cancelled'])->default('pending');
            $table->decimal('gross_amount', 10, 2)->comment('Valor bruto destinado ao repasse do provider.');
            $table->decimal('gateway_fee_amount', 10, 2)->default(0)->comment('Custo do gateway associado ao repasse.');
            $table->decimal('net_amount', 10, 2)->comment('Valor liquido do repasse: net_amount = gross_amount - gateway_fee_amount.');

            $table->timestamp('transferred_at')->nullable();
            $table->timestamp('failed_at')->nullable();
            $table->string('failure_code')->nullable();
            $table->text('failure_message')->nullable();
            $table->json('gateway_payload')->nullable();
            $table->json('metadata')->nullable();

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

            $table->index('payment_id');
            $table->index('provider_id');
            $table->index('status');
            $table->index('gateway_provider');
            $table->index('gateway_entity_reference');
            $table->index('gateway_operation_reference');
            $table->index('gateway_parent_reference');
            $table->index('gateway_transfer_target_reference');
            $table->index('transferred_at');
        });
    }

    public function down(): void
    {
        Schema::dropIfExists('payment_transfers');
    }
};
