-- 创建数据库
CREATE DATABASE IF NOT EXISTS message_archive CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
USE message_archive;
create or replace table message_archive.forum_posts
(
    id            int auto_increment
        primary key,
    tid           varchar(50)                           not null comment '帖子ID',
    fid           int                                   not null comment '板块ID',
    category_name varchar(50)                           null comment '板块名称',
    designation   varchar(100)                          null comment '番号',
    actress       varchar(100)                          null comment '出演女优',
    title         varchar(255)                          not null comment '标题',
    magnet_link   text                                  null comment '磁力链接',
    cover_image   varchar(500)                          null comment '封面图URL',
    post_url      varchar(255)                          not null comment '帖子链接',
    publish_date  varchar(20)                           null comment '发布时间',
    created_at    timestamp default current_timestamp() null,
    updated_at    timestamp default current_timestamp() null on update current_timestamp(),
    constraint tid
        unique (tid)
);

create or replace index forum_posts_designation_index
    on message_archive.forum_posts (designation);

create or replace index idx_actress
    on message_archive.forum_posts (actress);

create or replace table message_archive.messages
(
    id             int auto_increment comment '自增主键ID'
        primary key,
    group_id       varchar(20)  null comment '群ID',
    timestamp      varchar(20)  not null comment '消息时间戳',
    sender         varchar(255) not null comment '发送者微信ID',
    content        text         null comment '消息内容',
    message_type   varchar(50)  null comment '消息类型（文本、图片、视频等）',
    attachment_url text         null comment '附件URL（图片、视频链接）',
    message_id     varchar(32)  null comment '消息 id',
    message_xml    text         null comment '消息 xml 部分',
    raw_payload    longtext     null comment 'API 原始消息完整负载（完整序列化数据）',
    message_thumb  longtext     null comment '视频或图片消息的缩略图路径',
    image_path     varchar(255) null comment '图片URL路径'
)
    comment '微信群消息存储表，记录所有群聊消息';

create or replace index idx_date_timestamp
    on message_archive.messages (timestamp);

create or replace index idx_group_timestamp
    on message_archive.messages (group_id, timestamp);

create or replace index idx_message_sender
    on message_archive.messages (sender);

create or replace index idx_message_type
    on message_archive.messages (message_type);

create or replace index messages_message_id_index
    on message_archive.messages (message_id);

create or replace table message_archive.speech_counts
(
    id       int auto_increment comment '自增主键ID'
        primary key,
    group_id text null comment '群聊ID',
    wx_id    text null comment '用户微信ID',
    date     text null comment '统计日期（YYYY-MM-DD格式）',
    count    int  null comment '发言次数',
    constraint speech_counts_group_id_wx_id_date_uindex
        unique (group_id, wx_id, date) using hash
)
    comment '群成员每日发言统计表';

create or replace table message_archive.t_chatroom_member
(
    id                 int auto_increment
        primary key,
    chatroom_id        varchar(64)                            not null comment '群聊ID',
    wxid               varchar(64)                            not null comment '成员微信ID',
    nick_name          varchar(128)                           null comment '成员昵称',
    display_name       varchar(128)                           null comment '群内显示名称',
    inviter_user_name  varchar(64)                            null comment '邀请人微信ID',
    member_flag        int                                    null comment '成员标志，2049表示管理员',
    big_head_img_url   text                                   null comment '大头像URL',
    small_head_img_url text                                   null comment '小头像URL',
    is_owner           tinyint(1) default 0                   null comment '是否群主：0否，1是',
    is_admin           tinyint(1) default 0                   null comment '是否管理员：0否，1是',
    sex                tinyint                                null comment '性别：1男，2女，0未知',
    signature          text                                   null comment '个性签名',
    alias              varchar(128)                           null comment '微信号',
    country            varchar(64)                            null comment '国家',
    province           varchar(64)                            null comment '省份',
    city               varchar(64)                            null comment '城市',
    label_list         text                                   null comment '标签列表',
    phone_num_list     text                                   null comment '电话号码列表',
    py_initial         varchar(128)                           null comment '拼音首字母',
    quan_pin           varchar(256)                           null comment '全拼',
    remark_py_initial  varchar(128)                           null comment '备注拼音首字母',
    remark_quan_pin    varchar(256)                           null comment '备注全拼',
    create_time        datetime   default current_timestamp() not null comment '创建时间',
    update_time        datetime   default current_timestamp() not null on update current_timestamp() comment '更新时间',
    latest_active_time datetime                               null comment '最后活跃时间',
    status             tinyint    default 1                   null comment '1-在群里，2-已退群',
    constraint idx_chatroom_member
        unique (chatroom_id, wxid)
)
    comment '微信群成员信息表';

create or replace table message_archive.t_chatrooms
(
    id                 int auto_increment
        primary key,
    chatroom_id        varchar(64)                          not null comment '群聊ID',
    nick_name          varchar(128)                         null comment '群昵称',
    py_initial         varchar(128)                         null comment '群昵称拼音首字母',
    quan_pin           varchar(256)                         null comment '群昵称全拼',
    sex                tinyint                              null comment '性别',
    remark             varchar(128)                         null comment '备注',
    remark_py_initial  varchar(128)                         null comment '备注拼音首字母',
    remark_quan_pin    varchar(256)                         null comment '备注全拼',
    chat_room_notify   tinyint                              null comment '群通知',
    chat_room_owner    varchar(64)                          null comment '群主微信ID',
    chat_room_announcement text                             null comment '群公告内容',
    small_head_img_url text                                 null comment '群头像URL',
    member_list        text                                 null comment '成员列表(JSON)',
    create_time        datetime default current_timestamp() not null comment '创建时间',
    update_time        datetime default current_timestamp() not null on update current_timestamp() comment '更新时间',
    constraint idx_chatroom_id
        unique (chatroom_id)
)
    comment '微信群信息表';

create or replace table message_archive.t_encyclopedia_active_tasks
(
    active_task_id int auto_increment comment '任务ID'
        primary key,
    group_id       varchar(50)                                               not null comment '群聊ID',
    question       varchar(255)                                              not null comment '问题内容',
    answer         varchar(256)                                              not null comment '正确答案',
    score          int                                                       not null comment '答对可获得的分数',
    description    text                                                      null comment '问题描述或提示',
    holder_id      varchar(50)                                               not null comment '出题人ID',
    assigned_at    datetime                      default current_timestamp() null comment '任务分配时间',
    status         enum ('pending', 'completed') default 'pending'           null comment '任务状态',
    question_id    int                                                       null comment '问题ID'
)
    comment '百科答题游戏活跃任务表';

create or replace index group_id
    on message_archive.t_encyclopedia_active_tasks (group_id);

create or replace index question_id
    on message_archive.t_encyclopedia_active_tasks (question_id);

create or replace table message_archive.t_encyclopedia_groups
(
    group_id   varchar(50)                          not null comment '群聊ID'
        primary key,
    created_at datetime default current_timestamp() null comment '记录创建时间'
)
    comment '百科答题游戏群聊表';

create or replace table message_archive.t_encyclopedia_players
(
    player_id   varchar(50)                          not null comment '玩家ID（微信ID）',
    group_id    varchar(50)                          not null comment '群聊ID',
    player_name varchar(50)                          not null comment '玩家名称',
    points      int      default 0                   null comment '玩家积分',
    created_at  datetime default current_timestamp() null comment '记录创建时间',
    primary key (player_id, group_id)
)
    comment '百科答题游戏玩家表';

create or replace table message_archive.t_encyclopedia_task_history
(
    history_id     int auto_increment comment '历史记录ID'
        primary key,
    group_id       varchar(50)                            not null comment '群聊ID',
    active_task_id int                                    not null comment '关联的任务ID',
    player_id      varchar(50)                            not null comment '回答者ID',
    answer         varchar(256)                           not null comment '玩家的回答',
    is_correct     tinyint(1) default 0                   null comment '是否回答正确',
    points_earned  int        default 0                   null comment '获得的积分',
    completed_at   datetime   default current_timestamp() null comment '完成时间'
)
    comment '百科答题游戏任务历史表';

create or replace index group_id
    on message_archive.t_encyclopedia_task_history (group_id);

create or replace table message_archive.t_error_logs
(
    id            bigint auto_increment
        primary key,
    plugin_name   varchar(50)                          not null comment '插件名称',
    command       varchar(50)                          not null comment '触发的命令',
    user_id       varchar(50)                          not null comment '用户ID',
    group_id      varchar(50)                          null comment '群组ID，私聊为NULL',
    error_message text                                 not null comment '错误信息',
    stack_trace   text                                 null comment '堆栈跟踪',
    created_at    datetime default current_timestamp() not null comment '创建时间'
)
    comment '错误日志表';

create or replace index idx_created_at
    on message_archive.t_error_logs (created_at);

create or replace index idx_plugin_name
    on message_archive.t_error_logs (plugin_name);

create or replace table message_archive.t_group_stats
(
    id            bigint auto_increment
        primary key,
    group_id      varchar(50)   not null comment '群组ID',
    plugin_name   varchar(50)   not null comment '插件名称',
    command       varchar(50)   not null comment '触发的命令',
    total_calls   int default 0 not null comment '总调用次数',
    success_calls int default 0 not null comment '成功调用次数',
    failed_calls  int default 0 not null comment '失败调用次数',
    unique_users  int default 0 not null comment '唯一用户数',
    first_used_at datetime      not null comment '首次使用时间',
    last_used_at  datetime      not null comment '最后使用时间',
    constraint uk_group_plugin_command
        unique (group_id, plugin_name, command)
)
    comment '群组使用统计表';

create or replace index idx_group_id
    on message_archive.t_group_stats (group_id);

create or replace index idx_last_used_at
    on message_archive.t_group_stats (last_used_at);

create or replace table message_archive.t_group_command_user_stats
(
    id            bigint auto_increment
        primary key,
    group_id      varchar(50)                          not null comment '群组ID',
    plugin_name   varchar(50)                          not null comment '插件名称',
    command       varchar(50)                          not null comment '触发命令',
    user_id       varchar(50)                          not null comment '用户ID',
    first_used_at datetime                             not null comment '首次触发时间',
    last_used_at  datetime                             not null comment '最近触发时间',
    constraint uk_group_plugin_command_user
        unique (group_id, plugin_name, command, user_id)
)
    comment '群命令用户去重追踪表';

create or replace index idx_group_plugin_command
    on message_archive.t_group_command_user_stats (group_id, plugin_name, command);

create or replace index idx_group_command_user_last_used
    on message_archive.t_group_command_user_stats (last_used_at);

create or replace table message_archive.t_plugin_point_config
(
    id              int auto_increment
        primary key,
    plugin_name     varchar(100)         not null,
    points_required int        default 0 null,
    is_enabled      tinyint(1) default 1 null,
    description     text                 null,
    constraint plugin_name
        unique (plugin_name)
);

create or replace table message_archive.t_plugin_stats
(
    id               bigint auto_increment
        primary key,
    plugin_name      varchar(50)                          not null comment '插件名称',
    command          varchar(50)                          not null comment '触发的命令',
    stat_date        date                                 not null comment '统计日期',
    total_calls      int      default 0                   not null comment '总调用次数',
    success_calls    int      default 0                   not null comment '成功调用次数',
    failed_calls     int      default 0                   not null comment '失败调用次数',
    group_calls      int      default 0                   not null comment '群聊调用次数',
    private_calls    int      default 0                   not null comment '私聊调用次数',
    avg_process_time float    default 0                   not null comment '平均处理时间(毫秒)',
    created_at       datetime default current_timestamp() not null comment '创建时间',
    updated_at       datetime default current_timestamp() not null on update current_timestamp() comment '更新时间',
    constraint uk_plugin_command_date
        unique (plugin_name, command, stat_date)
)
    comment '插件统计汇总表';

create or replace index idx_stat_date
    on message_archive.t_plugin_stats (stat_date);

create or replace table message_archive.t_point_transactions
(
    id               int auto_increment
        primary key,
    user_id          varchar(100)                          not null,
    group_id         varchar(100)                          not null,
    transaction_type varchar(20)                           not null,
    points           int                                   not null,
    source           varchar(50)                           not null,
    description      text                                  null,
    created_at       timestamp default current_timestamp() null
);

create or replace table message_archive.t_prison_records
(
    id              int auto_increment
        primary key,
    user_id         varchar(100)                          not null,
    group_id        varchar(100)                          not null,
    start_time      timestamp default current_timestamp() null,
    end_time        timestamp                             not null,
    reason          varchar(255)                          null,
    status          tinyint   default 1                   null comment '1:在押 0:已释放',
    bailout_user_id varchar(100)                          null,
    bailout_time    timestamp                             null,
    created_at      timestamp default current_timestamp() null
);

create or replace table message_archive.t_push_feedback
(
    feedback_id varchar(36)                          not null
        primary key,
    task_id     varchar(36)                          not null,
    user_id     varchar(50)                          not null,
    content     text                                 not null,
    timestamp   datetime default current_timestamp() null
);

create or replace table message_archive.t_push_previews
(
    preview_id varchar(36)                                                        not null
        primary key,
    task_id    varchar(36)                                                        not null,
    content    longtext collate utf8mb4_bin                                       not null
        check (json_valid(`content`)),
    recipients longtext collate utf8mb4_bin                                       not null
        check (json_valid(`recipients`)),
    validation longtext collate utf8mb4_bin                                       null
        check (json_valid(`validation`)),
    status     enum ('sent', 'confirmed', 'modified') default 'sent'              null,
    created_at datetime                               default current_timestamp() null
);

create or replace table message_archive.t_push_task_logs
(
    log_id    varchar(36)                                            not null
        primary key,
    task_id   varchar(36)                                            not null,
    action    enum ('create', 'update', 'delete', 'pause', 'resume') not null,
    user_id   varchar(50)                                            not null,
    changes   longtext collate utf8mb4_bin                           null
        check (json_valid(`changes`)),
    timestamp datetime default current_timestamp()                   null
);

create or replace table message_archive.t_push_tasks
(
    task_id             varchar(36)                                                                                         not null
        primary key,
    name                varchar(50)                                                                                         not null,
    schedule_type       enum ('once', 'recurring')                                                                          not null,
    schedule_time       datetime                                                                                            not null,
    recurring_interval  enum ('daily', 'weekly', 'monthly')                                                                 null,
    recurring_end       datetime                                                                                            null,
    recurring_time      time                                                                                                null,
    weekly_days         longtext collate utf8mb4_bin                                                                        null
        check (json_valid(`weekly_days`)),
    monthly_day         int                                                                                                 null,
    content_text        text                                                                                                null,
    content_image       varchar(255)                                                                                        null,
    content_link        longtext collate utf8mb4_bin                                                                        null
        check (json_valid(`content_link`)),
    content_voice       varchar(255)                                                                                        null comment '语音消息文件路径',
    content_video       varchar(255)                                                                                        null comment '视频消息文件路径',
    content_miniprogram longtext collate utf8mb4_bin                                                                        null
        check (json_valid(`content_miniprogram`)),
    groups              longtext collate utf8mb4_bin                                                                        null
        check (json_valid(`groups`)),
    priority            enum ('high', 'medium', 'low')                                          default 'medium'            null,
    status              enum ('draft', 'scheduled', 'running', 'completed', 'failed', 'paused') default 'draft'             null,
    creator_id          varchar(50)                                                                                         not null,
    preview_recipients  longtext collate utf8mb4_bin                                                                        null
        check (json_valid(`preview_recipients`)),
    created_at          datetime                                                                default current_timestamp() null,
    updated_at          datetime                                                                default current_timestamp() null on update current_timestamp()
);

create or replace table message_archive.t_sign_history
(
    id            bigint auto_increment comment '历史记录ID'
        primary key,
    wx_id         varchar(100)                           not null comment '用户微信ID',
    group_id      varchar(100)                           not null comment '群聊ID',
    sign_date     date                                   not null comment '签到日期',
    sign_time     datetime                               not null comment '签到时间',
    is_makeup     tinyint(1) default 0                   null comment '是否为补签',
    points_earned int        default 0                   null comment '获得的积分',
    streak_count  int        default 1                   null comment '当时的连签天数',
    create_time   datetime   default current_timestamp() null comment '记录创建时间'
)
    comment '用户签到历史记录表';

create or replace index idx_sign_date
    on message_archive.t_sign_history (sign_date);

create or replace index idx_user_group
    on message_archive.t_sign_history (wx_id, group_id);

create or replace table message_archive.t_sign_record
(
    id                     bigint auto_increment comment '自增主键ID'
        primary key,
    wx_id                  varchar(100)                         not null comment '用户微信ID',
    group_id               varchar(100)                         not null comment '群聊ID',
    wx_nick_name           varchar(100)                         not null comment '用户昵称',
    points                 int      default 0                   null comment '积分数量',
    sign_stat              datetime                             null comment '最近签到时间',
    signin_streak          int      default 0                   null comment '连续签到天数',
    create_time            datetime default current_timestamp() null comment '记录创建时间',
    update_time            datetime default current_timestamp() null on update current_timestamp() comment '记录更新时间',
    last_sign_date         datetime                             null comment '上一次签到日期',
    streak_start_sign_date datetime                             null comment '连续签到第一天日期',
    last_continuous_days   int      default 0                   null comment '历史最长连续签到天数',
    total_sign_days        int      default 0                   null comment '总签到天数',
    previous_streak        int      default 0                   null comment '断签前的连签天数',
    constraint unique_sign
        unique (wx_id, group_id)
)
    comment '用户群内签到记录表';

create or replace table message_archive.t_user_levels
(
    id             bigint auto_increment
        primary key,
    user_id        varchar(100)                         not null,
    group_id       varchar(100)                         not null,
    exp            bigint   default 0                   null,
    level          int      default 1                   null,
    last_calc      datetime default current_timestamp() null,
    last_active_at datetime default current_timestamp() null,
    constraint uniq_user_group
        unique (user_id, group_id)
);

create or replace table message_archive.t_user_points
(
    id             int auto_increment
        primary key,
    user_id        varchar(100)                          not null,
    group_id       varchar(100)                          not null,
    total_points   int       default 0                   null,
    checkin_points int       default 0                   null,
    game_points    int       default 0                   null,
    other_points   int       default 0                   null,
    last_updated   timestamp default current_timestamp() null on update current_timestamp(),
    constraint user_id
        unique (user_id, group_id)
);

create or replace table message_archive.t_user_stats
(
    id            bigint auto_increment
        primary key,
    user_id       varchar(50)   not null comment '用户ID',
    plugin_name   varchar(50)   not null comment '插件名称',
    command       varchar(50)   not null comment '触发的命令',
    total_calls   int default 0 not null comment '总调用次数',
    success_calls int default 0 not null comment '成功调用次数',
    failed_calls  int default 0 not null comment '失败调用次数',
    first_used_at datetime      not null comment '首次使用时间',
    last_used_at  datetime      not null comment '最后使用时间',
    constraint uk_user_plugin_command
        unique (user_id, plugin_name, command)
)
    comment '用户使用统计表';

create or replace index idx_last_used_at
    on message_archive.t_user_stats (last_used_at);

create or replace index idx_user_id
    on message_archive.t_user_stats (user_id);

create or replace table message_archive.t_wechat_contacts
(
    id                 int auto_increment
        primary key,
    user_name          varchar(64)                          not null comment '微信ID',
    nick_name          varchar(128)                         null comment '昵称',
    py_initial         varchar(128)                         null comment '拼音首字母',
    quan_pin           varchar(256)                         null comment '全拼',
    sex                tinyint                              null comment '性别：1男，2女，0未知',
    remark             varchar(128)                         null comment '备注',
    remark_py_initial  varchar(128)                         null comment '备注拼音首字母',
    remark_quan_pin    varchar(256)                         null comment '备注全拼',
    signature          text                                 null comment '个性签名',
    alias              varchar(128)                         null comment '微信号',
    sns_bg_img         text                                 null comment '朋友圈背景图',
    country            varchar(64)                          null comment '国家',
    province           varchar(64)                          null comment '省份',
    city               varchar(64)                          null comment '城市',
    big_head_img_url   text                                 null comment '大头像URL',
    small_head_img_url text                                 null comment '小头像URL',
    description        text                                 null comment '描述',
    card_img_url       text                                 null comment '名片图片URL',
    label_list         text                                 null comment '标签列表',
    phone_num_list     text                                 null comment '电话号码列表',
    type               enum ('friends', 'chatrooms', 'ghs') not null comment '联系人类型：好友、群聊、公众号',
    create_time        datetime default current_timestamp() not null comment '创建时间',
    update_time        datetime default current_timestamp() not null on update current_timestamp() comment '更新时间',
    constraint idx_user_name
        unique (user_name)
)
    comment '微信联系人信息表';

create or replace table message_archive.t_xiuxian_clan
(
    clan_id        bigint auto_increment comment '门派ID'
        primary key,
    clan_name      varchar(100) not null comment '门派名称',
    group_id       varchar(100) not null comment '所属群ID',
    leader_user_id varchar(100) not null comment '掌门ID',
    constraint uk_group_clan_name
        unique (group_id, clan_name)
)
    comment '门派表' collate = utf8mb4_unicode_ci;

create or replace table message_archive.t_xiuxian_item
(
    item_id     int auto_increment comment '物品ID'
        primary key,
    name        varchar(100) not null comment '物品名称',
    type        varchar(50)  not null comment '物品类型',
    description text         null comment '物品描述',
    constraint uk_name
        unique (name)
)
    comment '物品定义表' collate = utf8mb4_unicode_ci;

create or replace table message_archive.t_xiuxian_player
(
    user_id             varchar(100)                 not null comment '平台用户ID'
        primary key,
    group_id            varchar(100)                 not null comment '主要所在群ID',
    dao_name            varchar(100)                 not null comment '道号',
    realm               varchar(50) default '凡人'   null comment '境界',
    spirit_root         varchar(50) default '凡灵根' null comment '灵根天赋',
    clan_id             bigint                       null comment '所属门派ID',
    cultivation_points  bigint      default 0        null comment '修为',
    spirit_stone        bigint      default 0        null comment '灵石',
    status              varchar(20) default 'Idle'   null comment '玩家状态',
    status_until        datetime                     null comment '状态到期时间',
    last_cultivate_time datetime                     null comment '上次闭关开始时间',
    constraint fk_clan_id
        foreign key (clan_id) references message_archive.t_xiuxian_clan (clan_id)
            on delete set null
)
    comment '玩家核心数据表' collate = utf8mb4_unicode_ci;

create or replace table message_archive.t_xiuxian_inventory
(
    id       bigint auto_increment comment '背包条目ID'
        primary key,
    user_id  varchar(100)  not null comment '玩家ID',
    item_id  int           not null comment '物品ID',
    quantity int default 0 not null comment '数量',
    constraint uk_user_item
        unique (user_id, item_id),
    constraint fk_inv_item
        foreign key (item_id) references message_archive.t_xiuxian_item (item_id)
            on delete cascade,
    constraint fk_inv_user
        foreign key (user_id) references message_archive.t_xiuxian_player (user_id)
            on delete cascade
)
    comment '玩家背包表' collate = utf8mb4_unicode_ci;

create or replace index idx_clan_id
    on message_archive.t_xiuxian_player (clan_id);

create or replace index idx_realm
    on message_archive.t_xiuxian_player (realm);

