-- 添加外键约束以确保数据完整性 (H2兼容版本)
-- V17__Add_foreign_key_constraints.sql

-- 使用H2兼容的方式添加外键约束

-- 为 api_keys 表添加 activity_id 外键约束
ALTER TABLE api_keys ADD CONSTRAINT fk_api_keys_activity
FOREIGN KEY (activity_id) REFERENCES activities(id) ON DELETE SET NULL;

-- 为 short_links 表添加 activity_id 外键约束
ALTER TABLE short_links ADD CONSTRAINT fk_short_links_activity
FOREIGN KEY (activity_id) REFERENCES activities(id) ON DELETE SET NULL;

-- 为 user_invites 表添加外键约束
ALTER TABLE user_invites DROP CONSTRAINT IF EXISTS fk_user_invites_activity;
ALTER TABLE user_invites ADD CONSTRAINT fk_user_invites_activity
FOREIGN KEY (activity_id) REFERENCES activities(id) ON DELETE CASCADE;

-- 为 link_clicks 表添加外键约束
ALTER TABLE link_clicks ADD CONSTRAINT fk_link_clicks_activity
FOREIGN KEY (activity_id) REFERENCES activities(id) ON DELETE SET NULL;

-- 为 daily_activity_stats 表添加外键约束
ALTER TABLE daily_activity_stats ADD CONSTRAINT fk_daily_stats_activity
FOREIGN KEY (activity_id) REFERENCES activities(id) ON DELETE CASCADE;

-- 为 activity_rewards 表添加外键约束
ALTER TABLE activity_rewards ADD CONSTRAINT fk_activity_rewards_activity
FOREIGN KEY (activity_id) REFERENCES activities(id) ON DELETE CASCADE;

-- 添加索引以优化查询性能
CREATE INDEX IF NOT EXISTS idx_user_invites_activity_invitee ON user_invites(activity_id, invitee_user_id);
CREATE INDEX IF NOT EXISTS idx_link_clicks_code ON link_clicks(code);
CREATE INDEX IF NOT EXISTS idx_link_clicks_activity ON link_clicks(activity_id);
CREATE INDEX IF NOT EXISTS idx_daily_stats_activity_date ON daily_activity_stats(activity_id, stat_date);
CREATE INDEX IF NOT EXISTS idx_reward_jobs_status ON reward_jobs(status);
CREATE INDEX IF NOT EXISTS idx_reward_jobs_next_run ON reward_jobs(next_run_at);
