CREATE TABLE IF NOT EXISTS data_permission_policy (
    id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
    tenant_id BIGINT UNSIGNED NOT NULL,
    policy_name VARCHAR(128) NOT NULL,
    project_scope VARCHAR(32) NOT NULL DEFAULT 'ALL' COMMENT 'ALL/IDS',
    project_ids_csv VARCHAR(2000) DEFAULT NULL,
    meeting_scope VARCHAR(32) NOT NULL DEFAULT 'ALL' COMMENT 'ALL/IDS',
    meeting_ids_csv VARCHAR(2000) DEFAULT NULL,
    module_scope VARCHAR(255) DEFAULT NULL,
    export_allowed TINYINT(1) NOT NULL DEFAULT 0,
    status VARCHAR(32) NOT NULL DEFAULT 'ENABLED',
    created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
    updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    KEY idx_tenant_status (tenant_id, status)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

CREATE TABLE IF NOT EXISTS role_data_permission (
    id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
    tenant_id BIGINT UNSIGNED NOT NULL,
    role_id BIGINT UNSIGNED NOT NULL,
    policy_id BIGINT UNSIGNED NOT NULL,
    created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
    UNIQUE KEY uk_tenant_role_policy (tenant_id, role_id, policy_id),
    KEY idx_policy (policy_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

INSERT INTO data_permission_policy (
    id, tenant_id, policy_name, project_scope, meeting_scope, module_scope, export_allowed, status
)
VALUES
    (1, 1, '默认全量策略', 'ALL', 'ALL', 'ALL', 1, 'ENABLED')
ON DUPLICATE KEY UPDATE
    policy_name = VALUES(policy_name),
    project_scope = VALUES(project_scope),
    meeting_scope = VALUES(meeting_scope),
    status = VALUES(status);

INSERT INTO role_data_permission (id, tenant_id, role_id, policy_id)
VALUES (1, 1, 101, 1)
ON DUPLICATE KEY UPDATE policy_id = VALUES(policy_id);

INSERT INTO permission (id, permission_code, permission_name, module)
VALUES
    (1025, 'data.permission.read', '查看数据权限策略', 'system'),
    (1026, 'data.permission.manage', '管理数据权限策略', 'system')
ON DUPLICATE KEY UPDATE permission_name = VALUES(permission_name), module = VALUES(module);

INSERT INTO role_permission (id, tenant_id, role_id, permission_id)
VALUES
    (25, 1, 101, 1025),
    (26, 1, 101, 1026)
ON DUPLICATE KEY UPDATE permission_id = VALUES(permission_id);
