#!/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> [options]
# Example: ./scripts/create-ephemeral.sh pr-42
# Example: ./scripts/create-ephemeral.sh pr-42 --ttl-days 7 --pr-numbers "42" --created-by mrojas
#
# Options:
#   --ttl-days N        TTL in days (sets ttl_expires_at tag). Default: no TTL tag.
#   --pr-numbers IDS    Comma-separated PR numbers (e.g. "42,56"). Default: none.
#   --created-by USER   GitHub username of creator. Default: none.
#   --yes, -y           Skip confirmation prompt (for CI/automation).
#
# 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+
set -euo pipefail

NAME="${1:?Usage: $0 <instance-name> [--ttl-days N] [--pr-numbers IDS] [--created-by USER]}"
shift
DIR="$(cd "$(dirname "$0")/.." && pwd)"

# Parse optional flags
TTL_DAYS=""
PR_NUMBERS=""
CREATED_BY=""
AUTO_APPROVE=false
while [[ $# -gt 0 ]]; do
  case "$1" in
    --ttl-days)   TTL_DAYS="$2"; shift 2 ;;
    --pr-numbers) PR_NUMBERS="$2"; shift 2 ;;
    --created-by) CREATED_BY="$2"; shift 2 ;;
    --yes|-y)     AUTO_APPROVE=true; shift ;;
    *) echo "Unknown option: $1"; exit 1 ;;
  esac
done

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"

if [[ "$AUTO_APPROVE" != true ]]; then
  echo ""
  echo "About to run terraform apply for ephemeral instance: ${NAME}"
  read -p "Continue? (y/N): " -n 1 -r
  echo
  if [[ ! $REPLY =~ ^[Yy]$ ]]; then
    echo "Aborted."
    terraform workspace select default 2>/dev/null
    exit 1
  fi
fi

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

trap - ERR

# ──────────────────────────────────────────────
# Tag ECS service with lifecycle metadata
# ──────────────────────────────────────────────

SERVICE_LABEL="ows-coda-${NAME}"
CLUSTER_NAME="qa-${SERVICE_LABEL}"

# Build tag list
TAGS="key=ephemeral,value=true"
if [[ -n "$TTL_DAYS" ]]; then
  EXPIRES_AT=$(date -u -d "+${TTL_DAYS} days" +%Y-%m-%dT%H:%M:%SZ 2>/dev/null \
    || date -u -v "+${TTL_DAYS}d" +%Y-%m-%dT%H:%M:%SZ)  # Linux || macOS
  TAGS="${TAGS} key=ttl_expires_at,value=${EXPIRES_AT} key=ttl_days,value=${TTL_DAYS}"
fi
[[ -n "$PR_NUMBERS" ]] && TAGS="${TAGS} key=pr_numbers,value=${PR_NUMBERS}"
[[ -n "$CREATED_BY" ]] && TAGS="${TAGS} key=created_by,value=${CREATED_BY}"

# Discover the ECS service ARN
SERVICE_ARN=$(aws ecs list-services --cluster "${CLUSTER_NAME}" --query "serviceArns[0]" --output text 2>/dev/null || true)
if [[ -n "$SERVICE_ARN" && "$SERVICE_ARN" != "None" ]]; then
  echo "==> Tagging ECS service: ${SERVICE_ARN}"
  aws ecs tag-resource --resource-arn "${SERVICE_ARN}" --tags ${TAGS}
else
  echo "WARNING: Could not discover ECS service ARN for tagging. Tags not applied."
fi

# ──────────────────────────────────────────────
# 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}"
