#!/usr/bin/env bash
# Fail deploy if production .env still points at localhost.
set -euo pipefail

ENV_FILE="${1:-node/.env}"

if [[ ! -f "$ENV_FILE" ]]; then
  echo "Error: $ENV_FILE not found" >&2
  exit 1
fi

# shellcheck disable=SC1090
source "$ENV_FILE"

if [[ "${NODE_ENV:-development}" != "production" ]]; then
  echo "NODE_ENV is not production — skipping URL check."
  exit 0
fi

fail=0
check_url() {
  local name="$1"
  local value="$2"
  if [[ -z "$value" ]]; then
    echo "Error: $name is empty" >&2
    fail=1
    return
  fi
  if [[ "$value" == *localhost* ]] || [[ "$value" == *127.0.0.1* ]]; then
    echo "Error: $name must not use localhost in production (got: $value)" >&2
    fail=1
  fi
  if [[ "$value" == *example.com* ]]; then
    echo "Error: $name still uses placeholder example.com (got: $value)" >&2
    fail=1
  fi
}

check_url APP_URL "${APP_URL:-}"
check_url BOOKING_APP_URL "${BOOKING_APP_URL:-$APP_URL}"
check_url API_URL "${API_URL:-}"
check_url CORS_ALLOWED_ORIGINS "${CORS_ALLOWED_ORIGINS:-}"

if [[ -n "${GOOGLE_CLIENT_ID:-}" ]]; then
  if [[ -z "${GOOGLE_AUTH_REDIRECT_URI:-}" ]]; then
    echo "Warning: GOOGLE_AUTH_REDIRECT_URI is not set — redirect URI is derived from the request Host."
    echo "  Add to Google Cloud Console → Authorized redirect URIs:"
    echo "  https://calendar.gventure.info/api/v1/auth/oauth/callback/google"
  else
    check_url GOOGLE_AUTH_REDIRECT_URI "${GOOGLE_AUTH_REDIRECT_URI}"
  fi
  if [[ -n "${GOOGLE_REDIRECT_URI:-}" ]]; then
    check_url GOOGLE_REDIRECT_URI "${GOOGLE_REDIRECT_URI}"
  fi
fi

if [[ "$fail" -ne 0 ]]; then
  echo "" >&2
  echo "Fix node/.env on the server:" >&2
  echo "  bash scripts/sync-production-env.sh    # keeps secrets, applies production URLs" >&2
  echo "  bash scripts/check-production-env.sh" >&2
  echo "Or edit node/.env using node/.env.production.example as reference." >&2
  exit 1
fi

echo "Production URL check passed."
echo "  APP_URL=$APP_URL"
echo "  BOOKING_APP_URL=${BOOKING_APP_URL:-$APP_URL}"
echo "  API_URL=$API_URL"
