CREATE TABLE IF NOT EXISTS players (
  id SERIAL PRIMARY KEY,
  first_name TEXT NOT NULL,
  last_name  TEXT NOT NULL,
  email TEXT UNIQUE,
  ranking INTEGER DEFAULT 0,
  created_at TIMESTAMP WITH TIME ZONE DEFAULT now()
);

CREATE TABLE IF NOT EXISTS tournaments (
  id SERIAL PRIMARY KEY,
  name TEXT NOT NULL,
  location TEXT,
  start_date DATE NOT NULL,
  end_date DATE NOT NULL,
  created_at TIMESTAMP WITH TIME ZONE DEFAULT now()
);

CREATE TABLE IF NOT EXISTS enrollments (
  player_id INTEGER NOT NULL REFERENCES players(id) ON DELETE CASCADE,
  tournament_id INTEGER NOT NULL REFERENCES tournaments(id) ON DELETE CASCADE,
  PRIMARY KEY (player_id, tournament_id)
);

CREATE TABLE IF NOT EXISTS teams (
  id SERIAL PRIMARY KEY,
  player1_id INTEGER NOT NULL REFERENCES players(id) ON DELETE CASCADE,
  player2_id INTEGER NOT NULL REFERENCES players(id) ON DELETE CASCADE,
  tournament_id INTEGER REFERENCES tournaments(id) ON DELETE CASCADE,
  UNIQUE(player1_id, player2_id, tournament_id)
);

CREATE TABLE IF NOT EXISTS matches (
  id SERIAL PRIMARY KEY,
  tournament_id INTEGER NOT NULL REFERENCES tournaments(id) ON DELETE CASCADE,
  court TEXT,
  round TEXT,
  scheduled_at TIMESTAMP WITH TIME ZONE,
  team_a_id INTEGER REFERENCES teams(id) ON DELETE SET NULL,
  team_b_id INTEGER REFERENCES teams(id) ON DELETE SET NULL,
  score_a INTEGER DEFAULT 0,
  score_b INTEGER DEFAULT 0,
  status TEXT DEFAULT 'scheduled' -- scheduled|playing|finished
);

-- Demo data
INSERT INTO players (first_name, last_name, email, ranking)
VALUES
  ('Flore', 'Van den Broeck', 'flore@example.com', 200),
  ('Karim', 'Hassan', 'karim@example.com', 210),
  ('Félicie', 'Hassan', 'felicie@example.com', 350),
  ('Balthazar', 'Hassan', 'balthazar@example.com', 400)
ON CONFLICT (email) DO NOTHING;

INSERT INTO tournaments (name, location, start_date, end_date)
SELECT 'Super Sunday - Demo', 'Les Églantiers, WSP', CURRENT_DATE, CURRENT_DATE
WHERE NOT EXISTS (SELECT 1 FROM tournaments WHERE name='Super Sunday - Demo');

-- auto-enroll demo players
DO $$
DECLARE t_id INT; p INT;
BEGIN
  SELECT id INTO t_id FROM tournaments WHERE name='Super Sunday - Demo';
  FOR p IN SELECT id FROM players LOOP
    INSERT INTO enrollments(player_id, tournament_id) VALUES (p, t_id)
    ON CONFLICT DO NOTHING;
  END LOOP;
END $$;