-- Migration: Change median calculation from 12 weeks to 4 weeks
-- Date: 2026-02-02
--
-- This migration updates projects_median_mv to calculate median based on
-- the last 4 weeks instead of 12 weeks.

DROP MATERIALIZED VIEW IF EXISTS projects_median_mv;

CREATE MATERIALIZED VIEW projects_median_mv AS
SELECT
    p.id AS project_id,
    p.user_id,
    PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY normalized_total_score) AS median_score
FROM (
    SELECT 
        project_id, 
        normalized_total_score,
        report_year,
        report_week,
        ROW_NUMBER() OVER (PARTITION BY project_id ORDER BY report_year DESC, report_week DESC) as rn
    FROM weekly_report_mv
    WHERE 
        (report_year < EXTRACT(ISOYEAR FROM CURRENT_DATE)::INTEGER)
        OR (report_year = EXTRACT(ISOYEAR FROM CURRENT_DATE)::INTEGER 
            AND report_week < EXTRACT(WEEK FROM CURRENT_DATE)::INTEGER)
) sub
JOIN projects p ON p.id = sub.project_id
WHERE rn <= 4 AND p.deleted = FALSE
GROUP BY p.id, p.user_id
WITH DATA;

CREATE INDEX idx_projects_median_mv_project_id ON projects_median_mv(project_id);
CREATE INDEX idx_projects_median_mv_user_id ON projects_median_mv(user_id);

COMMENT ON MATERIALIZED VIEW projects_median_mv IS 'Materialized view calculating median score for each project based on last 4 weeks of historical data. Includes user_id for multi-tenant support.';
