-- Migration 002: Add team field to users table
ALTER TABLE users ADD COLUMN IF NOT EXISTS team TEXT;

-- Refresh leaderboard view to include team
DROP MATERIALIZED VIEW IF EXISTS leaderboard;

CREATE MATERIALIZED VIEW leaderboard AS
SELECT
  u.id                                          AS user_id,
  u.full_name,
  u.team,
  RANK() OVER (ORDER BY COALESCE(SUM(t.points), 0) DESC) AS rank,
  COALESCE(SUM(t.points), 0)                   AS total_points,
  COUNT(t.id) FILTER (WHERE t.points IS NOT NULL) AS tips_count,
  COUNT(t.id) FILTER (WHERE t.points = 3)       AS exact_count,
  COUNT(t.id) FILTER (WHERE t.points = 1)       AS tendency_count
FROM users u
LEFT JOIN tips t ON t.user_id = u.id
GROUP BY u.id, u.full_name, u.team;

CREATE UNIQUE INDEX IF NOT EXISTS leaderboard_user_id_idx ON leaderboard (user_id);
