-- Migration: Revert optimization of weekly_report_mv
-- Date: 2026-01-26
--
-- This migration reverts:
-- 1. Removes created_date column from nodes table
-- 2. Drops indexes
-- 3. Restores MV to original structure (include current week, use entries.created_date)

-- ============================================
-- Step 1: Recreate MV with original structure
-- ============================================
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 idx_weekly_report_mv_project_year_week 
ON weekly_report_mv(project_id, report_year, report_week);

-- ============================================
-- Step 2: Drop indexes
-- ============================================
DROP INDEX IF EXISTS idx_nodes_project_user_created_date;
DROP INDEX IF EXISTS idx_nodes_created_date_user;

-- ============================================
-- Step 3: Remove created_date column from nodes
-- ============================================
ALTER TABLE nodes 
DROP COLUMN IF EXISTS created_date;

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.';
