#!/usr/bin/env bash
# Creates an ephemeral ows-coda environment sharing RDS, Redis, and S3 with the main QA env.
#
# Usage:  ./scripts/create-ephemeral.sh <instance-name>
# Example: ./scripts/create-ephemeral.sh pr-42
#
# Prerequisites:
#   - The default workspace must be applied first (shared resources must exist)
#   - AWS CLI configured with QA account credentials (data sources need API access)
#   - Terraform 1.14+
#   - mysql client (for DB creation via jump box or local tunnel)
set -euo pipefail

NAME="${1:?Usage: $0 <instance-name>}"
DIR="$(cd "$(dirname "$0")/.." && pwd)"

if [[ ! "$NAME" =~ ^[a-z][a-z0-9-]{0,20}$ ]]; then
  echo "Error: instance name must be lowercase alphanumeric with hyphens, 1-21 chars, starting with a letter."
  echo "       (Limited to 21 chars to stay within AWS resource name limits, e.g. 64-char IAM role names.)"
  exit 1
fi

echo "==> Creating ephemeral environment: qa-ows-coda-${NAME}"
cd "$DIR"

terraform init -input=false

# On failure: switch back to default workspace. If apply failed midway and left
# partial resources, run ./scripts/destroy-ephemeral.sh <name> to clean up.
cleanup() {
  echo ""
  echo "Apply failed. Workspace reset to default."
  echo "To clean up partial resources: ./scripts/destroy-ephemeral.sh ${NAME}"
  terraform workspace select default 2>/dev/null
}
trap cleanup ERR

terraform workspace new "$NAME" 2>/dev/null || terraform workspace select "$NAME"

echo "==> Running terraform apply..."
terraform apply -var="instance=${NAME}"

trap - ERR

# ──────────────────────────────────────────────
# Database setup instructions
# ──────────────────────────────────────────────

DB_NAME="coda_${NAME//-/_}"

echo ""
echo "WARNING: The Fargate task will fail health checks until the database exists."
echo ""
echo "Connect to the shared RDS cluster via jump box or local tunnel, then run:"
echo ""
echo "  CREATE DATABASE IF NOT EXISTS \`${DB_NAME}\`;"
echo "  GRANT ALL PRIVILEGES ON \`${DB_NAME}\`.* TO 'coda_svc'@'%';"
echo "  FLUSH PRIVILEGES;"
echo ""
echo "Then run Prisma migrations from the ows-coda repo:"
echo ""
echo "  DATABASE_URL=\"mysql://coda_svc:<password>@<rds-host>:3306/${DB_NAME}\" \\"
echo "    pnpm -F @ows-coda/db prisma migrate deploy"

URL=$(terraform output -raw url)

echo ""
echo "========================================"
echo "Ephemeral environment created!"
echo "========================================"
echo "URL:       ${URL}"
echo "Workspace: ${NAME}"
echo "Database:  ${DB_NAME}"
echo ""
echo "To destroy: ./scripts/destroy-ephemeral.sh ${NAME}"
