#!/usr/bin/env bash
# Infra — docker compose lifecycle + health waits

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
source "$SCRIPT_DIR/core"

TALENT_SCOUT_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"

infra_up() {
  log "Starting infrastructure (postgres:${POSTGRES_PORT}, redis:${REDIS_PORT})..."
  docker compose -f "$TALENT_SCOUT_ROOT/docker-compose.yml" up -d

  log "Waiting for PostgreSQL..."
  local retries=0
  while ! docker exec "$POSTGRES_CONTAINER" pg_isready -U postgres -q 2>/dev/null; do
    retries=$((retries + 1))
    if [ "$retries" -ge 30 ]; then
      err "PostgreSQL failed to become ready after 30s"
      exit 1
    fi
    sleep 1
  done
  ok "PostgreSQL ready"

  log "Waiting for Redis..."
  retries=0
  while ! docker exec "$REDIS_CONTAINER" redis-cli ping 2>/dev/null | grep -q PONG; do
    retries=$((retries + 1))
    if [ "$retries" -ge 30 ]; then
      err "Redis failed to become ready after 30s"
      exit 1
    fi
    sleep 1
  done
  ok "Redis ready"

  ok "Infrastructure up"
}

infra_down() {
  log "Stopping infrastructure..."
  docker compose -f "$TALENT_SCOUT_ROOT/docker-compose.yml" down
  ok "Infrastructure stopped"
}
