CREATE TABLE IF NOT EXISTS platform_menu (
    id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
    menu_code VARCHAR(64) NOT NULL,
    menu_name VARCHAR(64) NOT NULL,
    route_path VARCHAR(128) NOT NULL,
    permission_code VARCHAR(128) DEFAULT NULL,
    sort_no INT NOT NULL DEFAULT 100,
    status VARCHAR(32) NOT NULL DEFAULT 'ENABLED',
    is_deleted TINYINT(1) NOT NULL DEFAULT 0,
    created_by BIGINT UNSIGNED NOT NULL DEFAULT 0,
    created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
    updated_by BIGINT UNSIGNED NOT NULL DEFAULT 0,
    updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    UNIQUE KEY uk_platform_menu_code (menu_code),
    KEY idx_platform_menu_status_sort (status, sort_no)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

CREATE TABLE IF NOT EXISTS platform_role_menu (
    id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
    role_id BIGINT UNSIGNED NOT NULL,
    menu_id BIGINT UNSIGNED NOT NULL,
    UNIQUE KEY uk_platform_role_menu (role_id, menu_id),
    KEY idx_platform_role_menu_role (role_id),
    KEY idx_platform_role_menu_menu (menu_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

INSERT INTO platform_menu (id, menu_code, menu_name, route_path, permission_code, sort_no, status, is_deleted, created_by, updated_by)
VALUES
    (1, 'platform_tenant', '租户管理', '/platform/tenants', 'platform.tenant.manage', 10, 'ENABLED', 0, 0, 0),
    (2, 'platform_audit_log', '平台审计日志', '/platform/audit-logs', 'platform.audit.read', 20, 'ENABLED', 0, 0, 0)
ON DUPLICATE KEY UPDATE
    menu_name = VALUES(menu_name),
    route_path = VALUES(route_path),
    permission_code = VALUES(permission_code),
    sort_no = VALUES(sort_no),
    status = VALUES(status),
    is_deleted = VALUES(is_deleted),
    updated_at = CURRENT_TIMESTAMP;

INSERT INTO platform_role_menu (id, role_id, menu_id)
VALUES
    (1, 1, 1),
    (2, 1, 2)
ON DUPLICATE KEY UPDATE menu_id = VALUES(menu_id);
