<?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('affiliates', function (Blueprint $table) {
            $table->uuid('id')->primary();
            $table->uuid('user_id')->unique();
            $table->string('code', 12)->unique();
            $table->string('status')->default('active'); // active, paused, banned
            $table->integer('total_referrals')->default(0);
            $table->integer('qualified_referrals')->default(0);
            $table->integer('total_credits_earned')->default(0);
            $table->integer('pending_credits')->default(0);
            $table->timestamps();

            $table->foreign('user_id')->references('id')->on('users')->cascadeOnDelete();
        });

        Schema::create('affiliate_referrals', function (Blueprint $table) {
            $table->uuid('id')->primary();
            $table->uuid('affiliate_id');
            $table->uuid('referred_user_id');
            $table->string('affiliate_code');
            $table->string('status')->default('pending'); // pending, qualified, paid, cancelled
            $table->timestamp('registered_at');
            $table->timestamp('qualifies_at');
            $table->timestamp('paid_at')->nullable();
            $table->integer('credits_awarded')->default(0);
            $table->timestamps();

            $table->foreign('affiliate_id')->references('id')->on('affiliates')->cascadeOnDelete();
            $table->foreign('referred_user_id')->references('id')->on('users')->cascadeOnDelete();
            $table->index('status');
            $table->index('qualifies_at');
        });

        Schema::create('affiliate_credit_logs', function (Blueprint $table) {
            $table->uuid('id')->primary();
            $table->uuid('affiliate_id');
            $table->uuid('referral_id');
            $table->integer('credits');
            $table->string('reason');
            $table->timestamps();

            $table->foreign('affiliate_id')->references('id')->on('affiliates')->cascadeOnDelete();
        });
    }

    public function down(): void
    {
        Schema::dropIfExists('affiliate_credit_logs');
        Schema::dropIfExists('affiliate_referrals');
        Schema::dropIfExists('affiliates');
    }
};
