-- Migration: Add normalized_total_score to weekly_report_mv using weekly_goals.max_score
-- Date: 2026-01-24
--
-- normalized_total_score = LEAST(total_score, max_score) if max_score is set, else total_score.
-- Note: max_score is a snapshot field (filled only for new weeks by cron).

DROP MATERIALIZED VIEW IF EXISTS weekly_report_mv;

CREATE MATERIALIZED VIEW weekly_report_mv AS
SELECT
    p.id AS project_id,
    agg.report_year,
    agg.report_week,
    COALESCE(agg.total_score, 0.0000) AS total_score,
    CASE
        WHEN wg.max_score IS NULL THEN COALESCE(agg.total_score, 0.0000)
        ELSE LEAST(COALESCE(agg.total_score, 0.0000), wg.max_score)
    END AS normalized_total_score
FROM
    projects p
LEFT JOIN 
    (
        SELECT
            n.project_id,
            EXTRACT(ISOYEAR FROM e.created_date)::INTEGER AS report_year,
            EXTRACT(WEEK FROM e.created_date)::INTEGER AS report_week,
            SUM(n.score) AS total_score
        FROM
            nodes n
        JOIN
            entries e ON n.entry_id = e.id
        GROUP BY
            1, 2, 3
    ) agg 
    ON p.id = agg.project_id
LEFT JOIN
    weekly_goals wg
    ON wg.project_id = p.id
    AND wg.goal_year = agg.report_year
    AND wg.goal_week = agg.report_week
WHERE
    p.deleted = FALSE
ORDER BY
    p.id, agg.report_year, agg.report_week
WITH DATA;

CREATE INDEX IF NOT EXISTS idx_weekly_report_mv_project_year_week 
    ON weekly_report_mv(project_id, report_year, report_week);

COMMENT ON MATERIALIZED VIEW weekly_report_mv IS 'Materialized view aggregating weekly scores by project using ISOYEAR for correct week calculations at year boundaries. Includes all projects via LEFT JOIN. Adds normalized_total_score using weekly_goals.max_score snapshot.';

