-- V23: Add tracking_id to short_links table for full链路 tracking
-- Fix: PRD要求tracking_id全链路校验（点击->跳转->回调->奖励）

ALTER TABLE short_links ADD COLUMN IF NOT EXISTS tracking_id VARCHAR(64) UNIQUE;

CREATE INDEX IF NOT EXISTS idx_short_links_tracking_id ON short_links(tracking_id);

-- 添加 tracking_id 到 link_clicks 表
ALTER TABLE link_clicks ADD COLUMN IF NOT EXISTS tracking_id VARCHAR(64);
CREATE INDEX IF NOT EXISTS idx_link_clicks_tracking_id ON link_clicks(tracking_id);

-- 添加 tracking_id 到 user_rewards 表，记录归因
ALTER TABLE user_rewards ADD COLUMN IF NOT EXISTS tracking_id VARCHAR(64);

-- 创建tracking_mapping表，记录tracking_id与邀请关系的映射
CREATE TABLE IF NOT EXISTS tracking_mapping (
    id BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
    tracking_id VARCHAR(64) NOT NULL UNIQUE,
    activity_id BIGINT NOT NULL,
    inviter_user_id BIGINT NOT NULL,
    short_code VARCHAR(32) NOT NULL,
    source VARCHAR(50),
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    expires_at TIMESTAMP
);

CREATE INDEX IF NOT EXISTS idx_tracking_activity ON tracking_mapping(activity_id);
CREATE INDEX IF NOT EXISTS idx_tracking_inviter ON tracking_mapping(inviter_user_id);
