-- Migration: Create activity_contributions table
-- Description: 用户活动贡献记录表，用于实时显示最新贡献

-- 1. 创建 activity_contributions 表
CREATE TABLE IF NOT EXISTS activity_contributions (
    id BIGSERIAL PRIMARY KEY,
    activity_id BIGINT NOT NULL,
    user_id BIGINT NOT NULL,
    star_id BIGINT NOT NULL,
    item_id BIGINT NOT NULL,
    item_type VARCHAR(50) NOT NULL,
    quantity INTEGER NOT NULL DEFAULT 1,
    crystal_spent BIGINT NOT NULL,
    contribution_points BIGINT NOT NULL,
    created_at BIGINT NOT NULL
);

-- 2. 创建索引
CREATE INDEX IF NOT EXISTS idx_activity_contributions_activity ON activity_contributions(activity_id);
CREATE INDEX IF NOT EXISTS idx_activity_contributions_user_star ON activity_contributions(user_id, star_id);
CREATE INDEX IF NOT EXISTS idx_activity_contributions_created ON activity_contributions(created_at DESC);

-- 3. 添加外键约束
ALTER TABLE activity_contributions
    ADD CONSTRAINT fk_activity_contributions_activity FOREIGN KEY (activity_id) REFERENCES activities(id) ON DELETE CASCADE,
    ADD CONSTRAINT fk_activity_contributions_user FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE,
    ADD CONSTRAINT fk_activity_contributions_item FOREIGN KEY (item_id) REFERENCES activity_items(id) ON DELETE CASCADE,
    ADD CONSTRAINT fk_activity_contributions_star FOREIGN KEY (star_id) REFERENCES stars(star_id) ON DELETE CASCADE;

-- 4. 添加注释
COMMENT ON TABLE activity_contributions IS '用户活动贡献记录表';
COMMENT ON COLUMN activity_contributions.activity_id IS '活动ID';
COMMENT ON COLUMN activity_contributions.user_id IS '用户ID';
COMMENT ON COLUMN activity_contributions.star_id IS '粉丝身份ID';
COMMENT ON COLUMN activity_contributions.item_id IS '道具ID';
COMMENT ON COLUMN activity_contributions.item_type IS '道具类型';
COMMENT ON COLUMN activity_contributions.quantity IS '购买数量';
COMMENT ON COLUMN activity_contributions.crystal_spent IS '消耗水晶数';
COMMENT ON COLUMN activity_contributions.contribution_points IS '贡献点数';
COMMENT ON COLUMN activity_contributions.created_at IS '创建时间（毫秒时间戳）';