-- 第一模块：每日关键信号快照

CREATE TABLE IF NOT EXISTS daily_signal_snapshot (
    id BIGSERIAL PRIMARY KEY,
    signal_date DATE NOT NULL UNIQUE,
    status TEXT NOT NULL DEFAULT 'generated',
    new_models INTEGER NOT NULL DEFAULT 0,
    price_changes INTEGER NOT NULL DEFAULT 0,
    official_free INTEGER NOT NULL DEFAULT 0,
    aggregator_free INTEGER NOT NULL DEFAULT 0,
    unknown_free INTEGER NOT NULL DEFAULT 0,
    event_count INTEGER NOT NULL DEFAULT 0,
    page_mode TEXT NOT NULL DEFAULT 'standard',
    event_type_counts JSONB NOT NULL DEFAULT '{}'::jsonb,
    top_events JSONB NOT NULL DEFAULT '[]'::jsonb,
    source_audit TEXT,
    generated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
);

CREATE INDEX IF NOT EXISTS idx_daily_signal_snapshot_date ON daily_signal_snapshot(signal_date);
CREATE INDEX IF NOT EXISTS idx_daily_signal_snapshot_status ON daily_signal_snapshot(status);

COMMENT ON TABLE daily_signal_snapshot IS '第一模块产出的每日关键信号快照，用于日报与其他下游形态消费';
COMMENT ON COLUMN daily_signal_snapshot.top_events IS '已筛选的关键事件数组，JSONB 序列化 ModelEvent';
COMMENT ON COLUMN daily_signal_snapshot.event_type_counts IS '按事件类型聚合的数量统计';

DO $$
BEGIN
    IF NOT EXISTS (
        SELECT 1
        FROM pg_trigger
        WHERE tgname = 'daily_signal_snapshot_updated_at'
    ) THEN
        CREATE TRIGGER daily_signal_snapshot_updated_at
        BEFORE UPDATE ON daily_signal_snapshot
        FOR EACH ROW
        EXECUTE FUNCTION update_updated_at_column();
    END IF;
END
$$;
