<?php

/**
 * 文件功能：节日福利发放批次表迁移
 *
 * 将节日福利模板的每一次实际发放拆成独立批次，
 * 用于支持按年复用、连续多天、多轮次领取与历史追踪。
 */

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    /**
     * 创建 holiday_event_runs 表。
     */
    public function up(): void
    {
        Schema::create('holiday_event_runs', function (Blueprint $table) {
            $table->id();
            $table->unsignedBigInteger('holiday_event_id')->comment('所属节日福利模板 ID');

            // 批次快照：避免模板后续被修改后影响历史记录展示。
            $table->string('event_name', 100)->comment('活动名称快照');
            $table->text('event_description')->nullable()->comment('活动描述快照');
            $table->unsignedInteger('total_amount')->comment('总金币奖池快照');
            $table->unsignedInteger('max_claimants')->default(0)->comment('本批次最大领取人数（0=不限）');
            $table->enum('distribute_type', ['random', 'fixed'])->default('random')->comment('分配方式快照');
            $table->unsignedInteger('min_amount')->default(1)->comment('随机模式最低金额快照');
            $table->unsignedInteger('max_amount')->nullable()->comment('随机模式单人上限快照');
            $table->unsignedInteger('fixed_amount')->nullable()->comment('定额模式单人金额快照');
            $table->enum('target_type', ['all', 'vip', 'level'])->default('all')->comment('目标用户类型快照');
            $table->string('target_value', 50)->nullable()->comment('目标用户条件快照');
            $table->enum('repeat_type', ['once', 'daily', 'weekly', 'monthly', 'cron', 'yearly'])->default('once')->comment('模板重复方式快照');

            // 批次状态与时间。
            $table->dateTime('scheduled_for')->comment('本批次原定触发时间');
            $table->dateTime('triggered_at')->comment('本批次实际触发时间');
            $table->dateTime('expires_at')->nullable()->comment('本批次领取截止时间');
            $table->enum('status', ['active', 'completed', 'expired', 'cancelled'])->default('active')->comment('批次状态');

            // 统计信息。
            $table->unsignedInteger('audience_count')->default(0)->comment('本批次待领取总人数');
            $table->unsignedInteger('claimed_count')->default(0)->comment('本批次已领取人数');
            $table->unsignedInteger('claimed_amount')->default(0)->comment('本批次已领取金币总额');

            $table->timestamps();

            $table->foreign('holiday_event_id')->references('id')->on('holiday_events')->cascadeOnDelete();
            $table->index(['status', 'expires_at']);
            $table->index(['holiday_event_id', 'scheduled_for']);
        });
    }

    /**
     * 回滚 holiday_event_runs 表。
     */
    public function down(): void
    {
        Schema::dropIfExists('holiday_event_runs');
    }
};
