-- Migration Script: Reset trainers to Félia and Félix only
-- Run this in your Supabase SQL Editor

DO $$
DECLARE
  felia_id UUID;
  felix_id UUID;
  old_trainer_ids UUID[];
BEGIN
  -- Step 1: Get IDs of trainers to be replaced
  SELECT ARRAY[
    (SELECT id FROM trainers WHERE name = 'Emma'),
    (SELECT id FROM trainers WHERE name = 'Jake'),
    (SELECT id FROM trainers WHERE name = 'Mia'),
    (SELECT id FROM trainers WHERE name = 'Alex'),
    (SELECT id FROM trainers WHERE name = 'Sofia')
  ] INTO old_trainer_ids;

  -- Step 2: Create Félia if not exists
  SELECT COALESCE(
    (SELECT id FROM trainers WHERE name = 'Félia' LIMIT 1),
    gen_random_uuid()
  ) INTO felia_id;
  
  INSERT INTO trainers (id, name, specialty, color, workout_count, avatar_url)
  VALUES (felia_id, 'Félia', 'Core', '#30D158', 0, NULL)
  ON CONFLICT (id) DO UPDATE SET
    name = 'Félia',
    specialty = 'Core',
    color = '#30D158';

  -- Step 3: Create Félix if not exists
  SELECT COALESCE(
    (SELECT id FROM trainers WHERE name = 'Félix' LIMIT 1),
    gen_random_uuid()
  ) INTO felix_id;
  
  INSERT INTO trainers (id, name, specialty, color, workout_count, avatar_url)
  VALUES (felix_id, 'Félix', 'Strength', '#FFD60A', 0, NULL)
  ON CONFLICT (id) DO UPDATE SET
    name = 'Félix',
    specialty = 'Strength',
    color = '#FFD60A';

  -- Step 4: Get the final trainer IDs
  SELECT id INTO felia_id FROM trainers WHERE name = 'Félia';
  SELECT id INTO felix_id FROM trainers WHERE name = 'Félix';

  -- Step 5: Update workouts - female trainers → felia, male trainers → felix
  UPDATE workouts
  SET trainer_id = felia_id
  WHERE trainer_id IN (
    SELECT id FROM trainers WHERE name IN ('Emma', 'Mia', 'Sofia')
  );

  UPDATE workouts
  SET trainer_id = felix_id
  WHERE trainer_id IN (
    SELECT id FROM trainers WHERE name IN ('Jake', 'Alex')
  );

  -- Step 6: Update workout counts
  UPDATE trainers SET workout_count = (
    SELECT COUNT(*) FROM workouts WHERE trainer_id = felia_id
  ) WHERE id = felia_id;

  UPDATE trainers SET workout_count = (
    SELECT COUNT(*) FROM workouts WHERE trainer_id = felix_id
  ) WHERE id = felix_id;

  -- Step 7: Delete old trainers
  DELETE FROM trainers WHERE name IN ('Emma', 'Jake', 'Mia', 'Alex', 'Sofia');
END $$;

-- Step 8: Verify
SELECT 'Trainers:' AS result;
SELECT id::text, name, specialty, color, workout_count FROM trainers ORDER BY name;

SELECT 'Workout trainer distribution:' AS result;
SELECT trainer_id::text, COUNT(*) as workout_count FROM workouts GROUP BY trainer_id;
