#!/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 "▶ Démarrage/validation du service DB: ${DB_SVC}"
docker compose up -d "${DB_SVC}" >/dev/null

say "▶ Attente que Postgres réponde (pg_isready)"
start=$(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
  [ $(( $(date +%s) - start )) -ge "${WAIT_SECS}" ] && { err "❌ Postgres ne répond pas"; exit 1; }
  sleep 2
done
say "✅ Postgres prêt."

say "▶ Migration de la table teams (ajout name/tournament_id si absents, mapping depuis colonnes existantes)"
docker compose exec -T "${DB_SVC}" sh -lc "cat > /tmp/fix_teams.sql" <<'SQL'
-- Crée la table si absente (structure minimale)
DO $$
BEGIN
  IF NOT EXISTS (SELECT 1 FROM information_schema.tables WHERE table_name='teams') THEN
    CREATE TABLE teams (
      id SERIAL PRIMARY KEY
      -- on ajoutera name et tournament_id dans le bloc suivant
    );
  END IF;
END $$;

-- Ajoute la colonne name si absente
DO $$
DECLARE
  src_col text;
BEGIN
  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;
    -- Cherche une colonne plausible pour peupler name
    SELECT c.column_name INTO src_col
    FROM information_schema.columns c
    WHERE c.table_name='teams'
      AND c.column_name IN ('team_name','title','label','nom','libelle')
    ORDER BY c.column_name
    LIMIT 1;

    IF src_col IS NOT NULL THEN
      EXECUTE format('UPDATE teams SET name = %I WHERE name IS NULL', src_col);
    END IF;

    -- S'assure que name n'est pas NULL sur les lignes existantes
    UPDATE teams SET name = COALESCE(name, 'Team '||id);
  END IF;
END $$;

-- Ajoute tournament_id si absent (référence tournaments(id) si possible)
DO $$
BEGIN
  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;
    -- Ajoute une FK si la table tournaments existe
    IF EXISTS (SELECT 1 FROM information_schema.tables WHERE table_name='tournaments') THEN
      BEGIN
        ALTER TABLE teams
          ADD CONSTRAINT IF NOT EXISTS teams_tournament_fk
          FOREIGN KEY (tournament_id) REFERENCES tournaments(id) ON DELETE CASCADE;
      EXCEPTION WHEN duplicate_object THEN
        -- ignore
        NULL;
      END;
    END IF;
  END IF;
END $$;

-- Insère Alpha/Beta seulement s'ils n'existent pas déjà par le nom
WITH have_alpha AS (
  SELECT 1 FROM teams WHERE name ILIKE 'team alpha' LIMIT 1
), have_beta AS (
  SELECT 1 FROM teams WHERE name ILIKE 'team beta'  LIMIT 1
)
INSERT INTO teams (name, tournament_id)
SELECT v.name, v.tid
FROM (VALUES ('Team Alpha', 1), ('Team Beta', 1)) AS v(name, tid)
WHERE (v.name='Team Alpha' AND NOT EXISTS (SELECT 1 FROM have_alpha))
   OR (v.name='Team Beta'  AND NOT EXISTS (SELECT 1 FROM have_beta));
SQL

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

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

say "✅ Migration/seed teams terminé."