#!/usr/bin/env bash
#
# Wipe the local database and rebuild it from scratch, then power-cycle.
#
#   1. Tear down the Docker services AND their volumes (this destroys the database)
#   2. Bring postgres back up empty
#   3. Reapply all migrations
#   4. Reseed the test dealer accounts
#   5. Hand off to scripts/power-cycle.sh
#
# Use this when the database is broken beyond repair. For everyday restarts use
# `npm run power-cycle`, which preserves data.
#
# DESTRUCTIVE. Prompts for confirmation when attached to a terminal; otherwise
# requires --yes (or CLEAN_START_YES=1) so it can never wipe data unattended.

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() { printf '[clean-start] %s\n' "$*"; }

ASSUME_YES="${CLEAN_START_YES:-0}"
for arg in "$@"; do
  case "$arg" in
    -y | --yes) ASSUME_YES=1 ;;
    *)
      echo "unknown argument: $arg" >&2
      echo "usage: bash scripts/clean-start.sh [--yes]" >&2
      exit 2
      ;;
  esac
done

if ! command -v docker >/dev/null 2>&1 || ! docker info >/dev/null 2>&1; then
  log "docker is required for clean-start but is not available"
  exit 1
fi

# Later steps run npx/npm (prisma migrate, seed script); fail with a clear
# message on a fresh clone instead of a generic npx error mid-rebuild.
if [ ! -d "$PROJECT_ROOT/node_modules" ]; then
  log "node_modules not found; run 'npm install' first"
  exit 1
fi

if [ "$ASSUME_YES" != "1" ]; then
  if [ ! -t 0 ]; then
    log "refusing to destroy the database non-interactively; pass --yes if you mean it"
    exit 1
  fi
  log "This DESTROYS the local database and pgAdmin data (docker compose down -v)."
  log "The compose stack is SHARED BY EVERY WORKTREE, not just this one."
  log "Any dev server running in another worktree will lose its database."
  read -r -p "[clean-start] Type 'wipe' to continue: " reply
  if [ "$reply" != "wipe" ]; then
    log "aborted"
    exit 1
  fi
fi

PORT="$(resolve_port "$PROJECT_ROOT")"
log "stopping this worktree's dev server (PORT=$PORT)"
stop_local_dev "$PROJECT_ROOT" "$PORT"

# The compose stack is shared across worktrees (docker-compose.yml pins
# `name: amsoil-dlp`), so this wipes the one database every worktree uses.
log "tearing down containers and volumes"
docker compose down -v

log "starting an empty postgres"
docker compose up -d postgres

log "waiting for postgres to become healthy"
if ! wait_for_postgres; then
  log "postgres never became healthy; aborting before migrate"
  exit 1
fi
log "postgres healthy"

log "applying migrations"
npx prisma migrate deploy

log "seeding test dealers"
npm run seed-test-dealers

log "database rebuilt, handing off to power-cycle"
exec bash "$PROJECT_ROOT/scripts/power-cycle.sh"
