-- Add Celestial Events Menu
-- 添加天体事件展示菜单到数据管理菜单下

-- First check if menu already exists
DO $$
DECLARE
    menu_exists BOOLEAN;
BEGIN
    SELECT EXISTS(SELECT 1 FROM menus WHERE name = 'celestial_events') INTO menu_exists;

    IF NOT menu_exists THEN
        INSERT INTO "public"."menus"
        ("name", "title", "icon", "path", "component", "parent_id", "sort_order", "is_active")
        VALUES
        (
            'celestial_events',
            '天体事件',
            'CalendarOutlined',
            '/admin/celestial-events',
            NULL,
            2,  -- parent_id = 2 (数据管理)
            4,  -- sort_order = 4 (在NASA数据下载之后)
            true
        );
    END IF;
END $$;

-- Get the menu ID for role assignment
DO $$
DECLARE
    menu_id_var INTEGER;
    admin_role_id INTEGER;
    user_role_id INTEGER;
BEGIN
    -- Get the celestial_events menu ID
    SELECT id INTO menu_id_var FROM menus WHERE name = 'celestial_events';

    -- Get role IDs
    SELECT id INTO admin_role_id FROM roles WHERE name = 'admin';
    SELECT id INTO user_role_id FROM roles WHERE name = 'user';

    -- Assign menu to admin role
    IF menu_id_var IS NOT NULL AND admin_role_id IS NOT NULL THEN
        INSERT INTO role_menus (role_id, menu_id)
        VALUES (admin_role_id, menu_id_var)
        ON CONFLICT DO NOTHING;
    END IF;

    -- Assign menu to user role (users can view events)
    IF menu_id_var IS NOT NULL AND user_role_id IS NOT NULL THEN
        INSERT INTO role_menus (role_id, menu_id)
        VALUES (user_role_id, menu_id_var)
        ON CONFLICT DO NOTHING;
    END IF;
END $$;
