<?php

/**
 * 文件功能：创建聊天室礼包（红包）相关数据表
 *
 * red_packet_envelopes：红包主表（superlevel 用户发出的 888 金币红包）
 * red_packet_claims：红包领取记录（先到先得，每人只能领一次）
 *
 * @author  ChatRoom Laravel
 *
 * @version 1.0.0
 */

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('red_packet_envelopes', function (Blueprint $table) {
            $table->id();
            $table->unsignedBigInteger('sender_id')->comment('发包用户 ID');
            $table->string('sender_username', 20)->comment('发包用户名（快照）');
            $table->unsignedInteger('room_id')->comment('发出所在房间 ID');
            $table->unsignedInteger('total_amount')->comment('红包总金额（金币）');
            $table->unsignedInteger('total_count')->comment('红包总份数');
            $table->unsignedInteger('claimed_count')->default(0)->comment('已被领取份数');
            $table->unsignedInteger('claimed_amount')->default(0)->comment('已被领取总金额');
            $table->string('status', 10)->default('active')->comment('状态：active / completed / expired');
            $table->timestamp('expires_at')->comment('过期时间（超时未领完则关闭）');
            $table->timestamps();

            $table->index(['room_id', 'status']);
            $table->index('sender_id');
        });

        // 领取记录表
        Schema::create('red_packet_claims', function (Blueprint $table) {
            $table->id();
            $table->unsignedBigInteger('envelope_id')->comment('关联红包 ID');
            $table->unsignedBigInteger('user_id')->comment('领取用户 ID');
            $table->string('username', 20)->comment('领取用户名（快照）');
            $table->unsignedInteger('amount')->comment('本次领取金额');
            $table->timestamp('claimed_at')->useCurrent()->comment('领取时间');

            // 每人每个红包只能领一次
            $table->unique(['envelope_id', 'user_id']);
            $table->index('envelope_id');
            $table->foreign('envelope_id')->references('id')->on('red_packet_envelopes')->cascadeOnDelete();
        });
    }

    /**
     * 回滚：删除红包相关表。
     */
    public function down(): void
    {
        Schema::dropIfExists('red_packet_claims');
        Schema::dropIfExists('red_packet_envelopes');
    }
};
