-- ============================================================
-- Production Database Upgrade Script
-- ============================================================
-- This script upgrades the production database with the following changes:
-- 1. Add short_name to celestial_bodies
-- 2. Import menus and role_menus
-- 3. Import celestial_events
-- 4. Import scheduled_jobs
-- 5. Import system_settings
-- 6. Import user_follows
--
-- IMPORTANT: Run this script in a transaction and test on a backup first!
-- ============================================================

BEGIN;

-- ============================================================
-- 1. Add short_name column to celestial_bodies
-- ============================================================
DO $$
BEGIN
    IF NOT EXISTS (
        SELECT 1 FROM information_schema.columns
        WHERE table_name = 'celestial_bodies'
        AND column_name = 'short_name'
    ) THEN
        ALTER TABLE celestial_bodies ADD COLUMN short_name VARCHAR(50);
        RAISE NOTICE 'Added short_name column to celestial_bodies';
    ELSE
        RAISE NOTICE 'short_name column already exists';
    END IF;
END $$;

-- ============================================================
-- 2. Import menus and role_menus
-- ============================================================

-- Clear existing menus (will cascade to role_menus due to foreign key)
TRUNCATE TABLE menus CASCADE;
RAISE NOTICE 'Cleared existing menus and role_menus';

-- Disable triggers temporarily to handle circular foreign keys
ALTER TABLE menus DISABLE TRIGGER ALL;

-- Insert menus (parent menus first, then child menus)
INSERT INTO menus (id, parent_id, name, title, icon, path, component, sort_order, is_active, description, created_at, updated_at) VALUES
(1, NULL, 'dashboard', '控制台', 'dashboard', '/admin/dashboard', 'admin/Dashboard', 1, true, '系统控制台', '2025-11-28 18:07:11.767382', '2025-11-28 18:07:11.767382'),
(2, NULL, 'data_management', '数据管理', 'database', '', '', 2, true, '数据管理模块', '2025-11-28 18:07:11.767382', '2025-11-28 18:07:11.767382'),
(6, NULL, 'platform_management', '平台管理', 'settings', '', '', 3, true, '管理用户和系统参数', '2025-11-29 19:03:08.776597', '2025-11-29 19:03:08.776597'),
(14, NULL, 'user_profile', '个人资料', 'profile', '/user/profile', 'user/Profile', 1, true, '个人资料管理', '2025-12-18 16:26:11.778475', '2025-12-18 16:26:11.778475'),
(15, NULL, 'user_follow', '我的天体', 'star', '/user/follow', 'user/UserFollow', 2, true, '我关注的天体', '2025-12-18 16:27:48.688747', '2025-12-18 16:27:48.688747'),
(11, 2, 'star_systems', '恒星系统管理', 'StarOutlined', '/admin/star-systems', 'StarSystems', 1, true, '管理太阳系和系外恒星系统', '2025-12-06 02:35:21.137234', '2025-12-06 02:35:21.137234'),
(3, 2, 'celestial_bodies', '天体数据管理', NULL, '/admin/celestial-bodies', 'admin/CelestialBodies', 2, true, '查看和管理天体数据', '2025-11-28 18:07:11.767382', '2025-11-28 18:07:11.767382'),
(4, 2, 'static_data', '静态数据管理', NULL, '/admin/static-data', 'admin/StaticData', 2, true, '查看和管理静态数据（星座、星系等）', '2025-11-28 18:07:11.767382', '2025-11-28 18:07:11.767382'),
(5, 2, 'nasa_data', 'Horizon数据下载', NULL, '/admin/nasa-data', 'admin/NasaData', 3, true, '管理NASA Horizons数据下载', '2025-11-28 18:07:11.767382', '2025-11-28 18:07:11.767382'),
(13, 2, 'celestial_events', '天体事件', 'CalendarOutlined', '/admin/celestial-events', '', 4, true, '', '2025-12-15 03:20:39.798021', '2025-12-15 03:20:39.798021'),
(7, 6, 'user_management', '用户管理', NULL, '/admin/users', 'admin/Users', 1, true, '管理系统用户账号', '2025-11-29 19:03:08.776597', '2025-11-29 19:03:08.776597'),
(8, 6, 'platform_parameters_management', '平台参数管理', NULL, '/admin/settings', 'admin/Settings', 2, true, '管理系统通用配置参数', '2025-11-29 19:03:08.776597', '2025-11-29 19:03:08.776597'),
(12, 6, 'scheduled_jobs', '定时任务设置', 'ClockCircleOutlined', '/admin/scheduled-jobs', 'admin/ScheduledJobs', 5, true, '管理系统定时任务及脚本', '2025-12-10 17:42:38.031518', '2025-12-10 17:42:38.031518'),
(10, 6, 'system_tasks', '系统任务监控', 'schedule', '/admin/tasks', 'admin/Tasks', 30, true, '', '2025-11-30 16:04:59.572869', '2025-11-30 16:04:59.572869');

-- Re-enable triggers
ALTER TABLE menus ENABLE TRIGGER ALL;
RAISE NOTICE 'Imported menus data';

-- Reset sequence for menus
SELECT setval('menus_id_seq', (SELECT MAX(id) FROM menus));

-- Insert role_menus
INSERT INTO role_menus (role_id, menu_id) VALUES
-- Admin role (role_id = 1) has access to all menus
(1, 1), (1, 2), (1, 3), (1, 4), (1, 5), (1, 6), (1, 7), (1, 8), (1, 10), (1, 11), (1, 12), (1, 13), (1, 14), (1, 15),
-- User role (role_id = 2) has access to user menus only
(2, 14), (2, 15);

RAISE NOTICE 'Imported role_menus data';

-- ============================================================
-- 3. Import celestial_events (will be truncated and re-imported)
-- ============================================================
TRUNCATE TABLE celestial_events;
RAISE NOTICE 'Cleared existing celestial_events (data will be regenerated by scheduled jobs)';

-- ============================================================
-- 4. Import scheduled_jobs
-- ============================================================
-- Clear existing scheduled_jobs
TRUNCATE TABLE scheduled_jobs CASCADE;
RAISE NOTICE 'Cleared existing scheduled_jobs';

-- Insert scheduled_jobs
INSERT INTO scheduled_jobs (id, name, cron_expression, python_code, is_active, last_run_at, last_run_status, next_run_at, description, created_at, updated_at, job_type, predefined_function, function_params) VALUES
(1, '每日更新天体位置数据', '0 2 * * *', NULL, false, NULL, NULL, NULL, '每天凌晨2点自动从NASA Horizons下载主要天体的位置数据', '2025-12-10 17:43:01.234567', '2025-12-10 17:43:01.234567', 'predefined', 'download_positions_task', '{"body_ids": ["10", "199", "299", "399", "301", "499", "599", "699", "799", "899"], "days_range": "3"}'),
(2, '获取主要天体的食、合、冲等事件', '0 3 1 * *', NULL, true, NULL, NULL, NULL, '每月1日凌晨3点计算未来一年的主要天文事件', '2025-12-10 17:43:01.234567', '2025-12-10 17:43:01.234567', 'predefined', 'calculate_planetary_events', '{"body_ids": ["199", "299", "499", "599", "699", "799", "899"], "days_ahead": "365", "clean_old_events": true, "threshold_degrees": "5", "calculate_close_approaches": true}');

-- Reset sequence
SELECT setval('scheduled_jobs_id_seq', (SELECT MAX(id) FROM scheduled_jobs));
RAISE NOTICE 'Imported scheduled_jobs data';

-- ============================================================
-- 5. Import system_settings
-- ============================================================
-- Use INSERT ... ON CONFLICT to avoid duplicates
INSERT INTO system_settings (key, value, value_type, category, label, description, is_public, created_at, updated_at) VALUES
('view_mode', 'solar', 'string', 'ui', '默认视图模式', '系统默认的3D场景视图模式（solar或galaxy）', true, NOW(), NOW()),
('nasa_api_timeout', '120', 'int', 'api', 'NASA API超时时间', 'NASA Horizons API请求超时时间（秒）', false, NOW(), NOW()),
('auto_download_positions', 'False', 'bool', 'system', '自动下载位置数据', '当位置数据不存在时是否自动从NASA Horizons下载', false, NOW(), NOW())
ON CONFLICT (key) DO UPDATE SET
    value = EXCLUDED.value,
    value_type = EXCLUDED.value_type,
    category = EXCLUDED.category,
    label = EXCLUDED.label,
    description = EXCLUDED.description,
    is_public = EXCLUDED.is_public,
    updated_at = NOW();

RAISE NOTICE 'Imported/updated system_settings data';

-- ============================================================
-- 6. Import user_follows (keep existing data, don't truncate)
-- ============================================================
-- Note: user_follows should retain existing production data
-- This section is intentionally left empty to preserve user data
RAISE NOTICE 'Skipped user_follows import (preserving existing user data)';

-- ============================================================
-- Commit transaction
-- ============================================================
COMMIT;

-- ============================================================
-- Verification queries
-- ============================================================
\echo '============================================================'
\echo 'Upgrade completed successfully!'
\echo '============================================================'
\echo 'Verification:'
SELECT 'celestial_bodies.short_name exists:' as check,
       EXISTS(SELECT 1 FROM information_schema.columns WHERE table_name='celestial_bodies' AND column_name='short_name') as result;
SELECT 'menus count:' as check, COUNT(*) as result FROM menus;
SELECT 'role_menus count:' as check, COUNT(*) as result FROM role_menus;
SELECT 'scheduled_jobs count:' as check, COUNT(*) as result FROM scheduled_jobs;
SELECT 'system_settings count:' as check, COUNT(*) as result FROM system_settings;
\echo '============================================================'
