CREATE TABLE IF NOT EXISTS cp_weekly_rank_configs (
  app_code VARCHAR(32) NOT NULL DEFAULT 'lalu' COMMENT '应用编码',
  activity_code VARCHAR(64) NOT NULL DEFAULT 'cp_weekly_rank' COMMENT '活动编码',
  enabled TINYINT(1) NOT NULL DEFAULT 1 COMMENT '是否启用',
  relation_type VARCHAR(32) NOT NULL DEFAULT 'cp' COMMENT '关系类型，当前固定 cp',
  top_count INT NOT NULL DEFAULT 3 COMMENT '结算 Top 数量',
  updated_by_admin_id BIGINT NOT NULL DEFAULT 0 COMMENT '最后更新管理员',
  created_at_ms BIGINT NOT NULL COMMENT '创建时间，UTC epoch ms',
  updated_at_ms BIGINT NOT NULL COMMENT '更新时间，UTC epoch ms',
  PRIMARY KEY (app_code)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='CP 周榜配置表';

CREATE TABLE IF NOT EXISTS cp_weekly_rank_rewards (
  app_code VARCHAR(32) NOT NULL DEFAULT 'lalu' COMMENT '应用编码',
  rank_no INT NOT NULL COMMENT '名次',
  resource_group_id BIGINT NOT NULL COMMENT '奖励资源组 ID',
  created_at_ms BIGINT NOT NULL COMMENT '创建时间，UTC epoch ms',
  updated_at_ms BIGINT NOT NULL COMMENT '更新时间，UTC epoch ms',
  PRIMARY KEY (app_code, rank_no)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='CP 周榜名次奖励资源组表';

CREATE TABLE IF NOT EXISTS cp_weekly_rank_settlements (
  app_code VARCHAR(32) NOT NULL DEFAULT 'lalu' COMMENT '应用编码',
  settlement_id VARCHAR(96) NOT NULL COMMENT '发奖记录 ID',
  period_start_ms BIGINT NOT NULL COMMENT '周周期开始，UTC epoch ms',
  period_end_ms BIGINT NOT NULL COMMENT '周周期结束，UTC epoch ms',
  rank_no INT NOT NULL COMMENT '名次',
  relationship_id VARCHAR(128) NOT NULL COMMENT '获奖 CP 关系 ID',
  user_id BIGINT NOT NULL COMMENT '获奖用户 ID',
  score BIGINT NOT NULL DEFAULT 0 COMMENT '关系周榜分数',
  resource_group_id BIGINT NOT NULL COMMENT '发放资源组 ID',
  wallet_command_id VARCHAR(192) NOT NULL COMMENT 'wallet 发奖幂等键',
  wallet_grant_id VARCHAR(128) NOT NULL DEFAULT '' COMMENT 'wallet grant ID',
  status VARCHAR(32) NOT NULL COMMENT 'pending/running/granted/failed',
  failure_reason VARCHAR(512) NOT NULL DEFAULT '' COMMENT '失败原因',
  attempt_count INT NOT NULL DEFAULT 0 COMMENT '尝试次数',
  created_at_ms BIGINT NOT NULL COMMENT '创建时间，UTC epoch ms',
  updated_at_ms BIGINT NOT NULL COMMENT '更新时间，UTC epoch ms',
  PRIMARY KEY (app_code, settlement_id),
  UNIQUE KEY uk_cp_weekly_rank_period_user (app_code, period_start_ms, rank_no, relationship_id, user_id),
  UNIQUE KEY uk_cp_weekly_rank_wallet_command (app_code, wallet_command_id),
  KEY idx_cp_weekly_rank_pending (app_code, period_start_ms, period_end_ms, status, updated_at_ms)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='CP 周榜发奖事实表';
