#!/usr/bin/env bash
#
# Power-cycle the local development environment.
#
#   1. Stop this worktree's dev server (and its Stripe listener)
#   2. Clear Next.js build caches so nothing stale is served
#   3. Bring the Docker services up, preserving database data
#   4. Start the dev server again
#
# Data is preserved. To wipe and rebuild the database, use scripts/clean-start.sh.
#
# Invoked by `npm run power-cycle` and by app/api/dev-tools/power-cycle/route.ts.
# Output is teed to scripts/power-cycle.log, which the /dev-tools log viewer reads.

set -euo pipefail

PROJECT_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
cd "$PROJECT_ROOT"

# shellcheck source=scripts/lib/dev-env.sh
. "$PROJECT_ROOT/scripts/lib/dev-env.sh"

require_local_workstation "$PROJECT_ROOT"

LOG_FILE="$PROJECT_ROOT/scripts/power-cycle.log"
: >"$LOG_FILE"

log() { printf '[power-cycle] %s\n' "$*" | tee -a "$LOG_FILE"; }

PORT="$(resolve_port "$PROJECT_ROOT")"
export PORT
log "project: $PROJECT_ROOT (PORT=$PORT)"

# Scoped to this worktree: never touches another worktree's dev server.
log "stopping this worktree's dev server and stripe listener"
stop_local_dev "$PROJECT_ROOT" "$PORT"

log "clearing .next, node_modules/.cache and *.tsbuildinfo"
rm -rf .next node_modules/.cache
find . -maxdepth 1 -name '*.tsbuildinfo' -delete 2>/dev/null || true

# Only postgres and mailhog. The compose `app` service would run a second
# Next.js on the same port. Volumes are untouched, so data survives.
if command -v docker >/dev/null 2>&1 && docker info >/dev/null 2>&1; then
  log "starting docker services (postgres, mailhog)"
  docker compose up -d postgres mailhog 2>&1 | tee -a "$LOG_FILE" || true

  log "waiting for postgres to become healthy"
  if wait_for_postgres; then log "postgres healthy"; else log "postgres did not report healthy, continuing anyway"; fi
else
  log "docker unavailable, skipping services (expecting an external database)"
fi

if command -v stripe >/dev/null 2>&1 && grep -qs '^STRIPE_SECRET_KEY=..' .env.local; then
  log "forwarding stripe webhooks to localhost:$PORT"
  nohup stripe listen --forward-to "localhost:$PORT/api/webhooks/stripe" >>"$LOG_FILE" 2>&1 &
else
  log "stripe CLI or STRIPE_SECRET_KEY missing, skipping webhook forwarding"
fi

# Not `exec`: the pipeline forks a subshell anyway, so exec would not replace this
# process. Run it in the foreground so a detached caller keeps the server alive.
log "starting dev server on http://localhost:$PORT"
npm run dev 2>&1 | tee -a "$LOG_FILE"
