#!/usr/bin/env bash
set -euo pipefail

# Usage: ./create_match_with_teams.sh [TOURNAMENT_ID] [TEAM_A_NAME] [TEAM_B_NAME]
TID="${1:-1}"
TEAM_A="${2:-Team Alpha}"
TEAM_B="${3:-Team Beta}"

DB_SVC="${DB_SVC:-db}"
DB_NAME="${DB_NAME:-supersunday}"
DB_USER="${DB_USER:-postgres}"

say(){ printf "\033[1;36m%s\033[0m\n" "$*"; }
err(){ printf "\033[1;31m%s\033[0m\n" "$*" >&2; }

say "▶ Vérifie que la DB tourne"
docker compose up -d "${DB_SVC}" >/dev/null

say "▶ S’assure que teams a (id, name, tournament_id)"
docker compose exec -T "${DB_SVC}" sh -lc "cat > /tmp/ensure_teams_shape.sql" <<'SQL'
DO $$
BEGIN
  IF NOT EXISTS (SELECT 1 FROM information_schema.tables WHERE table_name='teams') THEN
    CREATE TABLE teams (id SERIAL PRIMARY KEY);
  END IF;

  IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name='teams' AND column_name='name') THEN
    ALTER TABLE teams ADD COLUMN name TEXT;
    UPDATE teams SET name = COALESCE(name, 'Team '||id);
  END IF;

  IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name='teams' AND column_name='tournament_id') THEN
    ALTER TABLE teams ADD COLUMN tournament_id INT NULL;
  END IF;
END $$;
SQL
docker compose exec -T "${DB_SVC}" sh -lc "psql -U ${DB_USER} -d ${DB_NAME} -f /tmp/ensure_teams_shape.sql"

say "▶ Upsert des équipes '${TEAM_A}' et '${TEAM_B}' pour le tournoi ${TID}"
docker compose exec -T "${DB_SVC}" sh -lc "cat > /tmp/upsert_teams.sql" <<'SQL'
\set team_a :'TEAM_A'
\set team_b :'TEAM_B'
\set tid    :TID

WITH
sel_a AS (
  SELECT id FROM teams
  WHERE name = :'team_a' AND (tournament_id = :tid OR tournament_id IS NULL)
  ORDER BY id LIMIT 1
),
ins_a AS (
  INSERT INTO teams (name, tournament_id)
  SELECT :'team_a', :tid
  WHERE NOT EXISTS (SELECT 1 FROM sel_a)
  RETURNING id
),
a AS (
  SELECT COALESCE((SELECT id FROM sel_a),(SELECT id FROM ins_a)) AS id
),
sel_b AS (
  SELECT id FROM teams
  WHERE name = :'team_b' AND (tournament_id = :tid OR tournament_id IS NULL)
  ORDER BY id LIMIT 1
),
ins_b AS (
  INSERT INTO teams (name, tournament_id)
  SELECT :'team_b', :tid
  WHERE NOT EXISTS (SELECT 1 FROM sel_b)
  RETURNING id
),
b AS (
  SELECT COALESCE((SELECT id FROM sel_b),(SELECT id FROM ins_b)) AS id
)
SELECT a.id AS team_a_id, b.id AS team_b_id FROM a, b;
SQL

IDS=$(
  docker compose exec -T "${DB_SVC}" sh -lc \
  "psql -U ${DB_USER} -d ${DB_NAME} -t -A -F',' \
     -v TEAM_A=\"${TEAM_A}\" -v TEAM_B=\"${TEAM_B}\" -v TID=${TID} \
     -f /tmp/upsert_teams.sql"
)

TEAM_A_ID="${IDS%%,*}"
TEAM_B_ID="${IDS##*,}"

if [[ -z "${TEAM_A_ID}" || -z "${TEAM_B_ID}" ]]; then
  err "❌ Impossible de déterminer les IDs d'équipes. Résultat: '${IDS}'"
  exit 1
fi
say "✅ Teams: ${TEAM_A} -> ${TEAM_A_ID}, ${TEAM_B} -> ${TEAM_B_ID}"

say "▶ Création du match via API"
JSON_PAYLOAD=$(printf '{"tournament_id":%s,"team_a_id":%s,"team_b_id":%s,"court":"Court 1"}' "$TID" "$TEAM_A_ID" "$TEAM_B_ID")
curl -s -X POST http://localhost/api/matches \
  -H "Content-Type: application/json" \
  --data-raw "${JSON_PAYLOAD}"
echo

say "▶ Matches du tournoi ${TID}"
curl -s "http://localhost/api/tournaments/${TID}/matches"
echo