<?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('transactions', function (Blueprint $table) {
            $table->id();
            $table->foreignId('organization_id')->constrained()->cascadeOnDelete();
            $table->foreignId('appointment_id')->constrained()->restrictOnDelete();
            $table->foreignId('patient_id')->constrained()->restrictOnDelete();
            $table->foreignId('location_id')->constrained()->restrictOnDelete();
            $table->foreignId('created_by_user_id')->nullable()->constrained('users')->nullOnDelete();
            $table->enum('type', ['payment', 'refund', 'waiver']);
            $table->decimal('amount', 12, 2);
            $table->string('method', 60)->nullable();
            $table->enum('status', ['pending', 'succeeded', 'failed', 'voided'])->default('succeeded')->index();
            $table->string('reference', 190)->nullable();
            $table->string('provider_reference', 190)->nullable();
            $table->string('idempotency_key', 120)->nullable();
            $table->string('receipt_number', 60)->nullable();
            $table->string('reason', 500)->nullable();
            $table->foreignId('reference_transaction_id')->nullable()->constrained('transactions')->nullOnDelete();
            $table->json('metadata')->nullable();
            $table->timestamps();

            $table->unique(['organization_id', 'idempotency_key'], 'transaction_idempotency_unique');
            $table->unique(['organization_id', 'receipt_number']);
            $table->index(['appointment_id', 'status']);
            $table->index(['patient_id', 'created_at']);
            $table->index(['location_id', 'created_at']);
        });
    }

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