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

ROOT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/.." && pwd)"
ENVIRONMENT="${1:-staging}"
[[ "$ENVIRONMENT" == dev || "$ENVIRONMENT" == staging || "$ENVIRONMENT" == production || "$ENVIRONMENT" == prod ]] || { echo "usage: build-next-app [dev|staging|production|prod]" >&2; exit 2; }
ENV_FILE="${CI_ENV_FILE:-}"
cleanup() { [[ -n "$ENV_FILE" && "$ENV_FILE" != "${CI_ENV_FILE:-}" ]] && rm -f "$ENV_FILE" || true; }
trap cleanup EXIT
if [[ -z "$ENV_FILE" && -z "${CI:-}" ]]; then ENV_FILE="$(mktemp)"; sh "$ROOT_DIR/scripts/export-env" "$ENVIRONMENT" > "$ENV_FILE"; fi
if [[ -n "$ENV_FILE" ]]; then
  bun dotenv -e "$ENV_FILE" -- bash "$ROOT_DIR/scripts/sync-convex-env" "$ENVIRONMENT" --from-current-env
  bun dotenv -e "$ENV_FILE" -- bash "$ROOT_DIR/scripts/convex-codegen"
else
  bash "$ROOT_DIR/scripts/sync-convex-env" "$ENVIRONMENT"
  bash "$ROOT_DIR/scripts/convex-codegen"
fi
args=(); [[ -z "$ENV_FILE" ]] || args+=(--env-file "$ENV_FILE")
docker compose "${args[@]}" -f "$ROOT_DIR/docker/compose.yml" build spoon-next
if [[ -n "$ENV_FILE" ]]; then
  CI_ENV_FILE="$ENV_FILE" bash "$ROOT_DIR/scripts/deploy-convex" "$ENVIRONMENT"
else
  bash "$ROOT_DIR/scripts/deploy-convex" "$ENVIRONMENT"
fi
