<?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('referrals', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->unsignedInteger('referrer_id');
            $table->unsignedInteger('referee_id')->nullable();
            $table->string('referee_email', 255);
            $table->string('referral_code', 32)->unique();
            $table->string('channel', 20)->default('email');
            $table->enum('status', [
                'pending',
                'signed_up',
                'order_placed',
                'shipped',
                'rewarded',
                'expired',
                'cancelled',
            ])->default('pending');
            $table->integer('qualifying_order_id')->nullable();
            $table->string('referee_ip', 45)->nullable();
            $table->string('referee_cookie', 64)->nullable();
            $table->timestamp('reminder_sent_at')->nullable();
            $table->timestamp('expires_at')->nullable();
            $table->timestamps();

            $table->index('referrer_id');
            $table->index('referee_id');
            $table->index('referee_email');
            $table->index('status');

            $table->foreign('referrer_id')->references('id')->on('members')->onDelete('cascade');
            $table->foreign('referee_id')->references('id')->on('members')->onDelete('set null');
            $table->foreign('qualifying_order_id')->references('id')->on('order')->onDelete('set null');
        });
    }

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