<?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
    {
        Schema::create('coupon_redemptions', function (Blueprint $table) {
            $table->id();

            $table->foreignIdFor(\App\Models\Coupon::class)->constrained()->cascadeOnDelete();
            $table->foreignUuid('checkout_session_id')->nullable()->constrained('checkout_sessions')->nullOnDelete();
            $table->foreignIdFor(\App\Models\Package::class)->nullable()->constrained()->nullOnDelete();
            $table->foreignIdFor(\App\Models\Tenant::class)->nullable()->constrained()->nullOnDelete();
            $table->foreignIdFor(\App\Models\User::class)->nullable()->constrained()->nullOnDelete();

            $table->string('paddle_transaction_id')->nullable();
            $table->string('status', 40)->default('pending');
            $table->text('failure_reason')->nullable();

            $table->decimal('amount_discounted', 10, 2)->default(0);
            $table->char('currency', 3)->default('EUR');
            $table->json('metadata')->nullable();

            $table->timestamp('redeemed_at')->nullable();

            $table->timestamps();

            $table->index(['status', 'redeemed_at']);
            $table->unique('paddle_transaction_id');
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::dropIfExists('coupon_redemptions');
    }
};
