-- ============================================================
-- MIGRATION 001: Multi-game rating system
-- Run this via psql or Supabase SQL editor
-- ============================================================

-- 1. Per-game player ratings (replaces chess-specific elo_ columns)
CREATE TABLE IF NOT EXISTS player_game_ratings (
  id UUID DEFAULT gen_random_uuid() PRIMARY KEY,
  player_id UUID NOT NULL REFERENCES auth.users(id) ON DELETE CASCADE,
  game_key TEXT NOT NULL,           -- chess, ludo, backgammon, domino
  mode TEXT NOT NULL DEFAULT 'default', -- chess: bullet/blitz/rapid/classical, others: 'default'
  rating INTEGER NOT NULL DEFAULT 1200,
  rating_deviation INTEGER DEFAULT 350,  -- for Glicko-2 later
  games_played INTEGER NOT NULL DEFAULT 0,
  wins INTEGER NOT NULL DEFAULT 0,
  losses INTEGER NOT NULL DEFAULT 0,
  draws INTEGER NOT NULL DEFAULT 0,
  win_streak INTEGER NOT NULL DEFAULT 0,
  best_win_streak INTEGER NOT NULL DEFAULT 0,
  last_played_at TIMESTAMPTZ,
  created_at TIMESTAMPTZ DEFAULT NOW(),
  updated_at TIMESTAMPTZ DEFAULT NOW(),
  UNIQUE(player_id, game_key, mode)
);

CREATE INDEX idx_pgr_player ON player_game_ratings(player_id);
CREATE INDEX idx_pgr_game_mode ON player_game_ratings(game_key, mode);
CREATE INDEX idx_pgr_leaderboard ON player_game_ratings(game_key, mode, rating DESC);

-- 2. Update XP levels to be game-neutral
UPDATE xp_levels SET title = 'Beginner', title_ar = 'مبتدئ' WHERE level = 1;
UPDATE xp_levels SET title = 'Rookie', title_ar = 'مستجد' WHERE level = 2;
UPDATE xp_levels SET title = 'Rookie II', title_ar = 'مستجد ٢' WHERE level = 3;
UPDATE xp_levels SET title = 'Regular', title_ar = 'لاعب' WHERE level = 4;
UPDATE xp_levels SET title = 'Regular II', title_ar = 'لاعب ٢' WHERE level = 5;
UPDATE xp_levels SET title = 'Skilled', title_ar = 'ماهر' WHERE level = 6;
UPDATE xp_levels SET title = 'Skilled II', title_ar = 'ماهر ٢' WHERE level = 7;
UPDATE xp_levels SET title = 'Expert', title_ar = 'خبير' WHERE level = 8;
UPDATE xp_levels SET title = 'Expert II', title_ar = 'خبير ٢' WHERE level = 9;
UPDATE xp_levels SET title = 'Master', title_ar = 'استاذ' WHERE level = 10;

-- 3. Migrate existing chess ratings from profiles to player_game_ratings
INSERT INTO player_game_ratings (player_id, game_key, mode, rating, games_played, wins, losses, draws)
SELECT
  id, 'chess', 'bullet',
  COALESCE(elo_bullet, 1200),
  0, 0, 0, 0
FROM profiles
WHERE elo_bullet IS NOT NULL AND elo_bullet != 1200
ON CONFLICT (player_id, game_key, mode) DO NOTHING;

INSERT INTO player_game_ratings (player_id, game_key, mode, rating, games_played, wins, losses, draws)
SELECT
  id, 'chess', 'blitz',
  COALESCE(elo_blitz, 1200),
  0, 0, 0, 0
FROM profiles
WHERE elo_blitz IS NOT NULL AND elo_blitz != 1200
ON CONFLICT (player_id, game_key, mode) DO NOTHING;

INSERT INTO player_game_ratings (player_id, game_key, mode, rating, games_played, wins, losses, draws)
SELECT
  id, 'chess', 'rapid',
  COALESCE(elo_rapid, 1200),
  0, 0, 0, 0
FROM profiles
WHERE elo_rapid IS NOT NULL AND elo_rapid != 1200
ON CONFLICT (player_id, game_key, mode) DO NOTHING;

INSERT INTO player_game_ratings (player_id, game_key, mode, rating, games_played, wins, losses, draws)
SELECT
  id, 'chess', 'classical',
  COALESCE(elo_classical, 1200),
  0, 0, 0, 0
FROM profiles
WHERE elo_classical IS NOT NULL AND elo_classical != 1200
ON CONFLICT (player_id, game_key, mode) DO NOTHING;

-- 4. Backfill per-game stats from rating_history
-- (count games per player per game_key per mode)
INSERT INTO player_game_ratings (player_id, game_key, mode, rating, games_played, wins, losses, draws, last_played_at)
SELECT
  rh.player_id,
  rh.game_key,
  rh.time_control_type,
  (SELECT rating_after FROM rating_history rh2
   WHERE rh2.player_id = rh.player_id
   AND rh2.game_key = rh.game_key
   AND rh2.time_control_type = rh.time_control_type
   ORDER BY rh2.created_at DESC LIMIT 1),
  COUNT(*),
  COUNT(*) FILTER (WHERE rh.result = 'win'),
  COUNT(*) FILTER (WHERE rh.result = 'loss'),
  COUNT(*) FILTER (WHERE rh.result = 'draw'),
  MAX(rh.created_at)
FROM rating_history rh
GROUP BY rh.player_id, rh.game_key, rh.time_control_type
ON CONFLICT (player_id, game_key, mode)
DO UPDATE SET
  games_played = EXCLUDED.games_played,
  wins = EXCLUDED.wins,
  losses = EXCLUDED.losses,
  draws = EXCLUDED.draws,
  rating = EXCLUDED.rating,
  last_played_at = EXCLUDED.last_played_at;

-- 5. RLS policies for player_game_ratings
ALTER TABLE player_game_ratings ENABLE ROW LEVEL SECURITY;

CREATE POLICY "Anyone can read ratings" ON player_game_ratings
  FOR SELECT USING (true);

CREATE POLICY "Service role can insert/update" ON player_game_ratings
  FOR ALL USING (true) WITH CHECK (true);

-- 6. Add last_daily_claim if it doesn't exist (some profiles use last_daily_reward)
-- ALTER TABLE profiles ADD COLUMN IF NOT EXISTS last_daily_claim DATE;

-- 7. Comment: Keep elo_* columns on profiles for now (backward compat)
-- They will be deprecated in favor of player_game_ratings
-- The API will write to BOTH during transition

COMMENT ON TABLE player_game_ratings IS 'Per-game, per-mode ratings. Replaces chess-specific elo_* columns on profiles.';
