<?php

declare(strict_types=1);

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->uuid('id')->primary();
            $table->foreignUuid('tenant_id')->constrained('tenants')->cascadeOnDelete();
            $table->foreignUuid('user_id')->nullable()->constrained('users')->nullOnDelete();
            $table->foreignUuid('payment_method_id')->constrained('payment_methods')->restrictOnDelete();
            $table->string('order_ref', 120);
            $table->unsignedBigInteger('amount');
            $table->string('currency', 8)->default('KRW');
            $table->enum('status', ['pending', 'authorized', 'captured', 'refunded', 'failed', 'cancelled'])->default('pending');
            $table->string('pg_tid', 191)->nullable();
            $table->json('pg_response')->nullable();
            $table->string('idempotency_key', 191);
            $table->timestamp('paid_at')->nullable();
            $table->timestamp('refunded_at')->nullable();
            $table->timestamps();

            $table->unique(['tenant_id', 'idempotency_key']);
            $table->index(['tenant_id', 'status', 'paid_at']);
            $table->index(['tenant_id', 'order_ref']);
        });
    }

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