#!/usr/bin/env bash
# Electric Store POS - Phase 1 database installer for macOS
# Requires PostgreSQL (Postgres.app from https://postgresapp.com, or Homebrew: brew install postgresql@16)
# Run: double-click this file (or: bash install-mac.command)
set -uo pipefail
cd "$(dirname "$0")"
echo; echo "=== Electric Store POS - Database Setup ==="; echo

PSQL_BIN=$(command -v psql || true)
for c in /Applications/Postgres.app/Contents/Versions/latest/bin/psql /opt/homebrew/opt/postgresql@16/bin/psql /usr/local/opt/postgresql@16/bin/psql; do
  [ -z "$PSQL_BIN" ] && [ -x "$c" ] && PSQL_BIN="$c"
done
if [ -z "$PSQL_BIN" ]; then
  echo "PostgreSQL was not found. Install Postgres.app from https://postgresapp.com, start it, then run this again."
  read -rp "Press Enter to close"; exit 1
fi
echo "Found PostgreSQL: $PSQL_BIN"
PGUSER_NAME=${PGUSER:-$(whoami)}
P="$PSQL_BIN -h localhost -U $PGUSER_NAME -v ON_ERROR_STOP=1 -q"

fail() { echo; echo "Setup stopped: $1"; read -rp "Press Enter to close"; exit 1; }

echo; echo "Running the test suite on a temporary database..."
$P -d postgres -c "DROP DATABASE IF EXISTS pos_test" -c "CREATE DATABASE pos_test" || fail "could not connect to PostgreSQL (is it running?)"
for f in db/migrations/*.sql; do $P -d pos_test -f "$f" || fail "migration $f"; done
$P -d pos_test -f db/tests/test_core.sql || fail "tests failed"
$P -d postgres -c "DROP DATABASE pos_test"
echo "All tests passed."

if [ "$($PSQL_BIN -h localhost -U $PGUSER_NAME -d postgres -tAc "SELECT 1 FROM pg_database WHERE datname='electric_pos'")" = "1" ]; then
  echo; echo "Database 'electric_pos' already exists - left unchanged to protect your data."
else
  echo; echo "Creating database 'electric_pos'..."
  $P -d postgres -c "CREATE DATABASE electric_pos" || fail "create database"
  for f in db/migrations/*.sql; do $P -d electric_pos -f "$f" || fail "migration $f"; done
  echo "Database 'electric_pos' is ready."
  echo "First login (once the app screens are built): admin / ChangeMe@123 - you will be asked to change it."
fi
read -rp "Press Enter to close"
