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

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

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

say "▶ Vérification/démarrage du service DB: ${DB_SVC}"
# Démarre s'il n'est pas déjà up
docker compose up -d "${DB_SVC}"

# Attente active jusqu’à ce que Postgres réponde
say "▶ Attente que Postgres réponde (pg_isready) — timeout ${WAIT_SECS}s"
start_ts=$(date +%s)
while true; do
  if docker compose exec -T "${DB_SVC}" sh -lc 'command -v pg_isready >/dev/null 2>&1 && pg_isready -U '"${DB_USER}"' -d '"${DB_NAME}"' -h 127.0.0.1 -p 5432 >/dev/null 2>&1'; then
    break
  fi
  now=$(date +%s)
  if [ $(( now - start_ts )) -ge "${WAIT_SECS}" ]; then
    err "❌ Postgres ne répond pas après ${WAIT_SECS}s. Vérifie les logs: docker compose logs --since=2m ${DB_SVC}"
    exit 1
  fi
  sleep 2
done
say "✅ Postgres prêt."

say "▶ Injection du SQL de seed (Alpha & Beta)"
docker compose exec -T "${DB_SVC}" sh -lc "cat > /tmp/seed_two_teams.sql" <<'SQL'
-- Crée la table teams si elle n'existe pas (schéma minimal compatible)
DO $$
BEGIN
  IF NOT EXISTS (
    SELECT 1 FROM information_schema.tables
    WHERE table_name='teams'
  ) THEN
    CREATE TABLE teams (
      id SERIAL PRIMARY KEY,
      name TEXT NOT NULL,
      tournament_id INT NULL REFERENCES tournaments(id) ON DELETE CASCADE
    );
  END IF;
END $$;

-- Insère Team Alpha / Team Beta. Si la colonne tournament_id existe,
-- associe par défaut au tournoi #1.
DO $$
BEGIN
  IF EXISTS (
    SELECT 1 FROM information_schema.columns
    WHERE table_name='teams' AND column_name='tournament_id'
  ) THEN
    INSERT INTO teams (name, tournament_id)
    VALUES ('Team Alpha', 1), ('Team Beta', 1)
    ON CONFLICT DO NOTHING;
  ELSE
    INSERT INTO teams (name)
    VALUES ('Team Alpha'), ('Team Beta')
    ON CONFLICT DO NOTHING;
  END IF;
END $$;
SQL

docker compose exec -T "${DB_SVC}" sh -lc "psql -U ${DB_USER} -d ${DB_NAME} -f /tmp/seed_two_teams.sql"

say "▶ Aperçu des équipes:"
docker compose exec -T "${DB_SVC}" sh -lc "psql -U ${DB_USER} -d ${DB_NAME} -c \"SELECT id, name, COALESCE(tournament_id, NULL) AS tournament_id FROM teams ORDER BY id LIMIT 20;\""

say '✅ Seed terminé.'