-- ============================================================
-- 年糕崽崽项目管理（PMS）同步服务初始化脚本（MySQL 5.7+ / 8.x）
-- 用法：mysql -u root -p < init.sql
-- 应用不执行任何建表/迁移（DDL），使用同步功能前必须先执行本脚本；
-- 应用连接账号只需要对 code_count 库的 SELECT/INSERT/UPDATE 权限。
-- 默认账号：liqi / qiqi991012（bcrypt 哈希存储，可在应用内注册新账号）
-- ============================================================

CREATE DATABASE IF NOT EXISTS code_count DEFAULT CHARSET utf8mb4;
USE code_count;

-- 应用账号（密码为 bcrypt 哈希）
CREATE TABLE IF NOT EXISTS users(
    id BIGINT PRIMARY KEY AUTO_INCREMENT,
    username VARCHAR(64) NOT NULL UNIQUE,
    password_hash VARCHAR(100) NOT NULL,
    created_at VARCHAR(32) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

-- Todo 同步表（按 user_id 隔离，LWW 以 updated_at 判定）
-- history 为生命周期轨迹 JSON：[{"status":"open","at":"..."},...]，记录每次进入某状态的时间
-- team_id>0 表示该条已共享给对应团队（团队管理员可见），0 为私密
CREATE TABLE IF NOT EXISTS sync_todos(
    user_id BIGINT NOT NULL,
    uuid CHAR(36) NOT NULL,
    title TEXT NOT NULL,
    content MEDIUMTEXT NOT NULL,
    project_name VARCHAR(255) NOT NULL DEFAULT '',
    due_at VARCHAR(32) NOT NULL DEFAULT '',
    priority VARCHAR(16) NOT NULL DEFAULT 'medium',
    status VARCHAR(16) NOT NULL DEFAULT 'open',
    history MEDIUMTEXT NOT NULL,
    team_id BIGINT NOT NULL DEFAULT 0,
    created_at VARCHAR(32) NOT NULL DEFAULT '',
    updated_at VARCHAR(32) NOT NULL,
    deleted TINYINT NOT NULL DEFAULT 0,
    PRIMARY KEY(user_id, uuid),
    KEY idx_sync_todos_updated(user_id, updated_at),
    KEY idx_sync_todos_team(team_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

-- 工单同步表
CREATE TABLE IF NOT EXISTS sync_tickets(
    user_id BIGINT NOT NULL,
    uuid CHAR(36) NOT NULL,
    title TEXT NOT NULL,
    description MEDIUMTEXT NOT NULL,
    type VARCHAR(16) NOT NULL DEFAULT 'task',
    project_name VARCHAR(255) NOT NULL DEFAULT '',
    start_at VARCHAR(32) NOT NULL DEFAULT '',
    due_at VARCHAR(32) NOT NULL DEFAULT '',
    status VARCHAR(16) NOT NULL DEFAULT 'open',
    priority VARCHAR(16) NOT NULL DEFAULT 'medium',
    history MEDIUMTEXT NOT NULL,
    team_id BIGINT NOT NULL DEFAULT 0,
    created_at VARCHAR(32) NOT NULL DEFAULT '',
    updated_at VARCHAR(32) NOT NULL,
    deleted TINYINT NOT NULL DEFAULT 0,
    PRIMARY KEY(user_id, uuid),
    KEY idx_sync_tickets_updated(user_id, updated_at),
    KEY idx_sync_tickets_team(team_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

-- 记事本同步表
CREATE TABLE IF NOT EXISTS sync_notes(
    user_id BIGINT NOT NULL,
    uuid CHAR(36) NOT NULL,
    content MEDIUMTEXT NOT NULL,
    updated_at VARCHAR(32) NOT NULL,
    deleted TINYINT NOT NULL DEFAULT 0,
    PRIMARY KEY(user_id, uuid),
    KEY idx_sync_notes_updated(user_id, updated_at)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

-- 按用户存储的同步设置（如加密盐 enc_salt、加密后的 AI API Key api_keys）。
-- api_keys 的值为 AES-256-GCM 密文（密钥由登录密码派生），服务器无法解密。
-- 另有全局资源行：日历节日背景图存为 fest_img:<节日名>，统一挂在管理员账号
-- （id=1）名下 —— 管理员在应用内上传推送，所有账号登录后拉取展示。
CREATE TABLE IF NOT EXISTS sync_settings(
    user_id BIGINT NOT NULL,
    name VARCHAR(64) NOT NULL,
    value MEDIUMTEXT NOT NULL,
    updated_at VARCHAR(32) NOT NULL,
    PRIMARY KEY(user_id, name)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

-- 旧版本升级：早期脚本建的 content/description 为 TEXT（64KB），
-- 待办/工单内容支持 Markdown 内嵌图片后需要 MEDIUMTEXT；重复执行无副作用。
ALTER TABLE sync_todos MODIFY content MEDIUMTEXT NOT NULL;
ALTER TABLE sync_tickets MODIFY description MEDIUMTEXT NOT NULL;

-- 旧版本升级：补 history 生命周期列（不存在时才添加，重复执行无副作用）。
SET @sql = IF((SELECT COUNT(*) FROM information_schema.COLUMNS
    WHERE TABLE_SCHEMA='code_count' AND TABLE_NAME='sync_todos' AND COLUMN_NAME='history')=0,
    'ALTER TABLE sync_todos ADD COLUMN history MEDIUMTEXT NOT NULL AFTER status', 'SELECT 1');
PREPARE st FROM @sql; EXECUTE st; DEALLOCATE PREPARE st;
SET @sql = IF((SELECT COUNT(*) FROM information_schema.COLUMNS
    WHERE TABLE_SCHEMA='code_count' AND TABLE_NAME='sync_tickets' AND COLUMN_NAME='history')=0,
    'ALTER TABLE sync_tickets ADD COLUMN history MEDIUMTEXT NOT NULL AFTER priority', 'SELECT 1');
PREPARE st FROM @sql; EXECUTE st; DEALLOCATE PREPARE st;

-- ============================================================
-- 团队协作（v2.1）：资料 / 团队 / 团队任务 / 日报 / 通知
-- ============================================================

-- 用户公开资料（同服务器用户互相可见：昵称/头衔/技术栈标签/头像缩略图）
CREATE TABLE IF NOT EXISTS user_profiles(
    user_id BIGINT PRIMARY KEY,
    nickname VARCHAR(64) NOT NULL DEFAULT '',
    title VARCHAR(64) NOT NULL DEFAULT '',
    email VARCHAR(128) NOT NULL DEFAULT '',
    bio VARCHAR(500) NOT NULL DEFAULT '',
    tech_tags VARCHAR(1000) NOT NULL DEFAULT '[]',
    avatar_thumb MEDIUMTEXT NOT NULL,
    updated_at VARCHAR(32) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

-- 团队（digest_time：日报 AI 摘要自动生成时间 HH:MM）
CREATE TABLE IF NOT EXISTS teams(
    id BIGINT PRIMARY KEY AUTO_INCREMENT,
    name VARCHAR(64) NOT NULL,
    owner_id BIGINT NOT NULL,
    digest_time VARCHAR(8) NOT NULL DEFAULT '21:00',
    created_at VARCHAR(32) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

-- 团队成员（role: owner | admin | member）
CREATE TABLE IF NOT EXISTS team_members(
    team_id BIGINT NOT NULL,
    user_id BIGINT NOT NULL,
    role VARCHAR(16) NOT NULL DEFAULT 'member',
    joined_at VARCHAR(32) NOT NULL,
    PRIMARY KEY(team_id, user_id),
    KEY idx_team_members_user(user_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

-- 团队任务/工单（服务器唯一真相，在线操作；kind: todo | ticket）
CREATE TABLE IF NOT EXISTS team_tasks(
    id BIGINT PRIMARY KEY AUTO_INCREMENT,
    team_id BIGINT NOT NULL,
    kind VARCHAR(16) NOT NULL DEFAULT 'todo',
    title TEXT NOT NULL,
    description MEDIUMTEXT NOT NULL,
    priority VARCHAR(16) NOT NULL DEFAULT 'medium',
    status VARCHAR(16) NOT NULL DEFAULT 'open',
    creator_id BIGINT NOT NULL,
    assignee_id BIGINT NOT NULL DEFAULT 0,
    start_at VARCHAR(32) NOT NULL DEFAULT '',
    due_at VARCHAR(32) NOT NULL DEFAULT '',
    urged_at VARCHAR(32) NOT NULL DEFAULT '',
    history MEDIUMTEXT NOT NULL,
    updated_at VARCHAR(32) NOT NULL,
    deleted TINYINT NOT NULL DEFAULT 0,
    KEY idx_team_tasks_team(team_id, deleted),
    KEY idx_team_tasks_assignee(assignee_id, deleted)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

-- 团队日报（date 为本地日期 YYYY-MM-DD）
CREATE TABLE IF NOT EXISTS team_reports(
    team_id BIGINT NOT NULL,
    user_id BIGINT NOT NULL,
    date CHAR(10) NOT NULL,
    content MEDIUMTEXT NOT NULL,
    submitted_at VARCHAR(32) NOT NULL,
    PRIMARY KEY(team_id, user_id, date)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

-- 团队日报 AI 摘要（管理员客户端生成，全员可见）
CREATE TABLE IF NOT EXISTS team_digests(
    team_id BIGINT NOT NULL,
    date CHAR(10) NOT NULL,
    content MEDIUMTEXT NOT NULL,
    provider VARCHAR(32) NOT NULL DEFAULT '',
    generated_at VARCHAR(32) NOT NULL,
    PRIMARY KEY(team_id, date)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

-- 团队通知（指派/催办/成员变动等；客户端同步时按 to_user 增量拉取转本地消息）
CREATE TABLE IF NOT EXISTS team_notices(
    id BIGINT PRIMARY KEY AUTO_INCREMENT,
    team_id BIGINT NOT NULL,
    to_user BIGINT NOT NULL,
    from_user BIGINT NOT NULL,
    kind VARCHAR(16) NOT NULL,
    ref_id VARCHAR(64) NOT NULL DEFAULT '',
    content TEXT NOT NULL,
    created_at VARCHAR(32) NOT NULL,
    KEY idx_team_notices_to(to_user, id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

-- 旧版本升级：个人待办/工单支持按条共享到团队（team_id=0 私密；重复执行无副作用）。
SET @sql = IF((SELECT COUNT(*) FROM information_schema.COLUMNS
    WHERE TABLE_SCHEMA='code_count' AND TABLE_NAME='sync_todos' AND COLUMN_NAME='team_id')=0,
    'ALTER TABLE sync_todos ADD COLUMN team_id BIGINT NOT NULL DEFAULT 0 AFTER history', 'SELECT 1');
PREPARE st FROM @sql; EXECUTE st; DEALLOCATE PREPARE st;
SET @sql = IF((SELECT COUNT(*) FROM information_schema.COLUMNS
    WHERE TABLE_SCHEMA='code_count' AND TABLE_NAME='sync_tickets' AND COLUMN_NAME='team_id')=0,
    'ALTER TABLE sync_tickets ADD COLUMN team_id BIGINT NOT NULL DEFAULT 0 AFTER history', 'SELECT 1');
PREPARE st FROM @sql; EXECUTE st; DEALLOCATE PREPARE st;
SET @sql = IF((SELECT COUNT(*) FROM information_schema.STATISTICS
    WHERE TABLE_SCHEMA='code_count' AND TABLE_NAME='sync_todos' AND INDEX_NAME='idx_sync_todos_team')=0,
    'ALTER TABLE sync_todos ADD KEY idx_sync_todos_team(team_id)', 'SELECT 1');
PREPARE st FROM @sql; EXECUTE st; DEALLOCATE PREPARE st;
SET @sql = IF((SELECT COUNT(*) FROM information_schema.STATISTICS
    WHERE TABLE_SCHEMA='code_count' AND TABLE_NAME='sync_tickets' AND INDEX_NAME='idx_sync_tickets_team')=0,
    'ALTER TABLE sync_tickets ADD KEY idx_sync_tickets_team(team_id)', 'SELECT 1');
PREPARE st FROM @sql; EXECUTE st; DEALLOCATE PREPARE st;

-- 默认账号 liqi（密码 qiqi991012 的 bcrypt 哈希）；已存在则跳过，不会覆盖改过的密码
INSERT IGNORE INTO users(username, password_hash, created_at)
VALUES ('liqi', '$2a$10$XWBtGPu9xYRyr8diFEfvBeEHRkO6pa3CDduE09OurJztuXVcJZOB2', '2026-08-11T13:20:00Z');
