<?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('payments', function (Blueprint $table) {
            $table->id();
            $table->foreignId('schedule_id')->constrained('schedules')->onDelete('cascade');
            $table->foreignId('client_id')->constrained('clients')->onDelete('cascade');
            $table->foreignId('provider_id')->nullable()->constrained('providers')->nullOnDelete();
            $table->foreignId('client_payment_method_id')->nullable()->constrained('client_payment_methods')->nullOnDelete();

            $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->enum('payment_method', ['credit_card', 'pix', 'boleto']);
            $table->enum('status', ['pending', 'processing', 'authorized', 'paid', 'failed', 'cancelled'])->default('pending');

            $table->decimal('gross_amount', 10, 2)->comment('Valor bruto cobrado do cliente.');
            $table->decimal('gateway_fee_amount', 10, 2)->default(0)->comment('Taxa cobrada pelo gateway nesta cobranca.');
            $table->decimal('platform_fee_amount', 10, 2)->default(0)->comment('Taxa da plataforma (regra interna), sem impacto na formula de net_amount.');
            $table->decimal('net_amount', 10, 2)->comment('Valor liquido apos taxa do gateway: net_amount = gross_amount - gateway_fee_amount.');
            $table->string('currency', 3)->default('BRL');
            $table->unsignedTinyInteger('installments')->default(1);

            $table->timestamp('authorized_at')->nullable();
            $table->timestamp('paid_at')->nullable();
            $table->timestamp('failed_at')->nullable();
            $table->timestamp('cancelled_at')->nullable();
            $table->timestamp('expires_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('schedule_id');
            $table->index('client_id');
            $table->index('provider_id');
            $table->index('status');
            $table->index('payment_method');
            $table->index('gateway_provider');
            $table->index('gateway_entity_reference');
            $table->index('gateway_operation_reference');
            $table->index('paid_at');
        });
    }

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