<?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('referral_rewards', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->unsignedBigInteger('referral_id')->nullable();
            $table->unsignedInteger('member_id');
            $table->enum('type', ['referrer', 'referee']);
            $table->integer('coupon_id')->nullable();
            $table->string('coupon_code', 50)->nullable();
            $table->decimal('amount', 8, 2)->default(5.00);
            $table->enum('status', [
                'pending',
                'issued',
                'redeemed',
                'expired',
                'revoked',
            ])->default('pending');
            $table->timestamp('issued_at')->nullable();
            $table->timestamp('redeemed_at')->nullable();
            $table->timestamp('revoked_at')->nullable();
            $table->string('revoke_reason', 255)->nullable();
            $table->unsignedInteger('admin_id')->nullable();
            $table->timestamps();

            $table->unique(['referral_id', 'type'], 'referral_rewards_referral_type_unique');
            $table->foreign('referral_id')->references('id')->on('referrals')->onDelete('cascade');
            $table->foreign('member_id')->references('id')->on('members')->onDelete('cascade');
            $table->foreign('coupon_id')->references('id')->on('coupons')->onDelete('set null');
        });
    }

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