-- Migration: Fix weekly_report_mv to use ISOYEAR instead of YEAR
-- This fixes incorrect week calculations at year boundaries
-- Date: 2024

-- Drop existing materialized view
DROP MATERIALIZED VIEW IF EXISTS weekly_report_mv;

-- Recreate materialized view with ISOYEAR
CREATE MATERIALIZED VIEW weekly_report_mv AS
SELECT
    n.project_id,
    -- 🔑 ГЛАВНОЕ ИСПРАВЛЕНИЕ: Используем ISOYEAR
    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
WITH DATA;

-- Recreate index
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';

