-- V4: RBAC foundation + admin upgrade logs (Spring Boot 3 optimization)

CREATE TABLE IF NOT EXISTS rbac_role
(
    id          INTEGER      NOT NULL PRIMARY KEY AUTO_INCREMENT,
    code        VARCHAR(50)  NOT NULL,
    name        VARCHAR(100) NOT NULL,
    description VARCHAR(255),
    enabled     INTEGER      NOT NULL DEFAULT 1,
    create_time DATETIME,
    update_time DATETIME
);

CREATE TABLE IF NOT EXISTS rbac_user_role
(
    id          INTEGER NOT NULL PRIMARY KEY AUTO_INCREMENT,
    user_id     INTEGER NOT NULL,
    role_id     INTEGER NOT NULL,
    create_time DATETIME
);

CREATE TABLE IF NOT EXISTS upgrade_log
(
    id         INTEGER NOT NULL PRIMARY KEY AUTO_INCREMENT,
    version    VARCHAR(50)  NOT NULL,
    title      VARCHAR(200) NOT NULL,
    content    TEXT,
    type       VARCHAR(50),
    created_by INTEGER,
    create_time DATETIME
);

INSERT INTO rbac_role (code, name, description, enabled, create_time, update_time)
SELECT 'ADMIN', '管理员', '后台管理与运维权限', 1, NOW(), NOW()
WHERE NOT EXISTS (SELECT 1 FROM rbac_role WHERE code = 'ADMIN');

INSERT INTO rbac_role (code, name, description, enabled, create_time, update_time)
SELECT 'USER', '普通用户', '论坛基础访问权限', 1, NOW(), NOW()
WHERE NOT EXISTS (SELECT 1 FROM rbac_role WHERE code = 'USER');

INSERT INTO rbac_user_role (user_id, role_id, create_time)
SELECT u.id, r.id, NOW()
FROM user u
JOIN rbac_role r ON r.code = 'USER'
WHERE NOT EXISTS (
    SELECT 1 FROM rbac_user_role ur WHERE ur.user_id = u.id AND ur.role_id = r.id
);

INSERT INTO rbac_user_role (user_id, role_id, create_time)
SELECT u.id, r.id, NOW()
FROM user u
JOIN rbac_role r ON r.code = 'ADMIN'
WHERE u.level >= 1
  AND NOT EXISTS (
    SELECT 1 FROM rbac_user_role ur WHERE ur.user_id = u.id AND ur.role_id = r.id
);

INSERT INTO upgrade_log (version, title, content, type, created_by, create_time)
SELECT 'v3.5.13',
       '后台管理与RBAC架构初始化',
       '新增角色与用户角色映射；新增后台管理与运维面板；新增升级日志管理入口。',
       'feature',
       1,
       NOW()
WHERE NOT EXISTS (
    SELECT 1 FROM upgrade_log WHERE version = 'v3.5.13' AND title = '后台管理与RBAC架构初始化'
);
