#!/bin/bash
# Production commands for @analytics
# Sourced by the top-level ./run script — do not execute directly.
# ROOT_DIR is set by the caller.

ENV_FILE="$ROOT_DIR/infrastructure/.env.prod"
COMPOSE_FILE="$ROOT_DIR/infrastructure/docker-compose.prod.yaml"

_require_env() {
  if [ ! -f "$ENV_FILE" ]; then
    echo "ERROR: $ENV_FILE not found."
    echo "  cp infrastructure/.env.prod.example infrastructure/.env.prod"
    echo "  # then fill in all CHANGE_ME values"
    exit 1
  fi
}

case "${2:-}" in
  up)
    # ./run prod:up
    _require_env
    docker compose -f "$COMPOSE_FILE" --env-file "$ENV_FILE" up -d
    echo "Production stack started."
    echo "  Collector  → 127.0.0.1:4001"
    echo "  API        → 127.0.0.1:4003"
    echo "  Realtime   → 127.0.0.1:4004"
    echo "  TimescaleDB external → :25434"
    ;;

  down)
    # ./run prod:down
    docker compose -f "$COMPOSE_FILE" --env-file "$ENV_FILE" down
    echo "Production stack stopped."
    ;;

  restart)
    # ./run prod:restart [service]
    SERVICE="${3:-}"
    if [ -n "$SERVICE" ]; then
      docker compose -f "$COMPOSE_FILE" --env-file "$ENV_FILE" restart "$SERVICE"
    else
      docker compose -f "$COMPOSE_FILE" --env-file "$ENV_FILE" restart
    fi
    ;;

  status)
    # ./run prod:status
    echo "=== Containers ==="
    docker compose -f "$COMPOSE_FILE" ps
    echo ""
    echo "=== Collector  (port 4001) ==="
    curl -sf http://localhost:4001/health/live && echo "" || echo "Not running"
    echo "=== API        (port 4003) ==="
    curl -sf http://localhost:4003/health/live && echo "" || echo "Not running"
    echo "=== Realtime   (port 4004) ==="
    curl -sf http://localhost:4004/health/live && echo "" || echo "Not running"
    ;;

  logs)
    # ./run prod:logs [service]
    SERVICE="${3:-}"
    if [ -n "$SERVICE" ]; then
      docker compose -f "$COMPOSE_FILE" --env-file "$ENV_FILE" logs -f "$SERVICE"
    else
      docker compose -f "$COMPOSE_FILE" --env-file "$ENV_FILE" logs -f
    fi
    ;;

  keygen)
    # ./run prod:keygen — generate a new COLLECTOR_WRITE_KEY
    KEY=$(openssl rand -hex 32)
    echo ""
    echo "Generated write key:"
    echo ""
    echo "  COLLECTOR_WRITE_KEY=$KEY"
    echo ""
    echo "Add to infrastructure/.env.prod, then set the same value as"
    echo "'writeKey' in the AnalyticsConfig passed to AnalyticsProvider."
    echo ""
    ;;

  *)
    echo "Unknown prod command: prod:${2}"
    echo "Usage: ./run prod:<up|down|restart|status|logs|keygen>"
    exit 1
    ;;
esac
