-- Revert to one row per (project_id, user_id, entry_message)

DROP MATERIALIZED VIEW IF EXISTS project_score_sample_mv;

CREATE MATERIALIZED VIEW project_score_sample_mv AS
WITH entry_scores AS (
  SELECT
    n.project_id,
    n.entry_id,
    n.user_id,
    SUM(n.score) AS score,
    MAX(n.created_date) AS created_date
  FROM nodes n
  GROUP BY n.project_id, n.entry_id, n.user_id
),
with_message AS (
  SELECT
    es.project_id,
    es.score,
    e.text AS entry_message,
    es.user_id,
    es.created_date
  FROM entry_scores es
  JOIN entries e ON e.id = es.entry_id
)
SELECT DISTINCT ON (project_id, user_id, entry_message)
  project_id,
  score,
  entry_message,
  user_id,
  created_date
FROM with_message
ORDER BY project_id, user_id, entry_message, created_date DESC
WITH DATA;

CREATE INDEX idx_project_score_sample_mv_project_score_user ON project_score_sample_mv(project_id, score, user_id);
CREATE INDEX idx_project_score_sample_mv_user_id ON project_score_sample_mv(user_id);

COMMENT ON MATERIALIZED VIEW project_score_sample_mv IS 'One row per (project_id, user_id, entry_message): representative row (latest by date).';
