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

ROOT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/.." && pwd)"
GENERATED_DIR="$ROOT_DIR/packages/backend/convex/_generated"

if [[ -z "${CONVEX_SELF_HOSTED_URL:-}" ]]; then
  if [[ -n "${CONVEX_URL:-}" ]]; then
    export CONVEX_SELF_HOSTED_URL="$CONVEX_URL"
  elif [[ -n "${NEXT_PUBLIC_CONVEX_URL:-}" ]]; then
    export CONVEX_SELF_HOSTED_URL="$NEXT_PUBLIC_CONVEX_URL"
  fi
fi

has_generated_files() {
  [[ -f "$GENERATED_DIR/api.js" ]] \
    && [[ -f "$GENERATED_DIR/api.d.ts" ]] \
    && [[ -f "$GENERATED_DIR/server.js" ]] \
    && [[ -f "$GENERATED_DIR/server.d.ts" ]] \
    && [[ -f "$GENERATED_DIR/dataModel.d.ts" ]]
}

has_self_hosted_env() {
  [[ -n "${CONVEX_SELF_HOSTED_URL:-}" ]] \
    && [[ -n "${CONVEX_SELF_HOSTED_ADMIN_KEY:-}" ]]
}

has_cloud_deployment_env() {
  [[ -n "${CONVEX_DEPLOYMENT:-}" ]]
}

if has_self_hosted_env || has_cloud_deployment_env; then
  cd "$ROOT_DIR"
  bun patch:usesend
  cd "$ROOT_DIR/packages/backend"
  bun run codegen
  exit 0
fi

if has_generated_files; then
  echo "Convex generated files already exist; skipping codegen because no deployment env is configured."
  exit 0
fi

cat >&2 <<'EOF'
Convex generated files are missing.

Run this command with either:
  - CONVEX_SELF_HOSTED_URL and CONVEX_SELF_HOSTED_ADMIN_KEY, or
  - CONVEX_DEPLOYMENT

CI should provide these through its env file before running checks.
EOF
exit 1
