-- V74: 创建用户标签表
-- 对应PRD要求: user.tag.add, user.tag.view

-- 创建用户标签表
CREATE TABLE IF NOT EXISTS sys_user_tag (
    id BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
    user_id BIGINT NOT NULL,
    tag_name VARCHAR(50) NOT NULL,
    tag_color VARCHAR(20) DEFAULT '#1890ff',
    created_by BIGINT,
    created_at TIMESTAMP(3) DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP(3) DEFAULT CURRENT_TIMESTAMP,
    deleted_at TIMESTAMP(3),
    CONSTRAINT uk_user_tag UNIQUE (user_id, tag_name)
);

CREATE INDEX IF NOT EXISTS idx_sys_user_tag_user_id ON sys_user_tag(user_id);
CREATE INDEX IF NOT EXISTS idx_sys_user_tag_tag_name ON sys_user_tag(tag_name);

-- 为已有角色添加用户标签权限
INSERT INTO sys_role_permission (role_id, permission_id)
SELECT r.id, p.id
FROM sys_role r
CROSS JOIN sys_permission p
WHERE r.role_code = 'super_admin'
AND p.permission_code IN ('user.tag.add', 'user.tag.view')
AND NOT EXISTS (
    SELECT 1 FROM sys_role_permission rp
    WHERE rp.role_id = r.id AND rp.permission_id = p.id
);

INSERT INTO sys_role_permission (role_id, permission_id)
SELECT r.id, p.id
FROM sys_role r
CROSS JOIN sys_permission p
WHERE r.role_code = 'system_admin'
AND p.permission_code IN ('user.tag.add', 'user.tag.view')
AND NOT EXISTS (
    SELECT 1 FROM sys_role_permission rp
    WHERE rp.role_id = r.id AND rp.permission_id = p.id
);

INSERT INTO sys_role_permission (role_id, permission_id)
SELECT r.id, p.id
FROM sys_role r
CROSS JOIN sys_permission p
WHERE r.role_code = 'operation_manager'
AND p.permission_code IN ('user.tag.add', 'user.tag.view')
AND NOT EXISTS (
    SELECT 1 FROM sys_role_permission rp
    WHERE rp.role_id = r.id AND rp.permission_id = p.id
);
