#!/usr/bin/env bash
#
# Load `database/dev-snapshot.sql` into the running dockerized Postgres.
#
# Runs idempotently: every INSERT in the snapshot is data-only and the
# tables it touches already exist via the migrations. If you've already
# imported, re-running will fail on duplicate PKs — see the optional
# --reset flag.
#
# Usage:
#   ./database/import-dev-snapshot.sh             # import on top of current data
#   ./database/import-dev-snapshot.sh --reset     # truncate everything first
#
# Windows users (PowerShell / cmd) — run the equivalent one-liner:
#   Get-Content -Encoding UTF8 database\dev-snapshot.sql | docker compose exec -T postgres psql -U sehat -d sehat_sahoolat
set -e

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
SNAPSHOT="$SCRIPT_DIR/dev-snapshot.sql"

if [ ! -f "$SNAPSHOT" ]; then
  echo "✗ missing $SNAPSHOT" >&2
  exit 1
fi

# Make sure postgres is up
if ! docker compose ps --status running postgres | grep -q sehat-postgres; then
  echo "✗ sehat-postgres isn't running. Start it with: docker compose up -d postgres" >&2
  exit 1
fi

if [ "${1:-}" = "--reset" ]; then
  echo "[import] --reset — truncating all data tables…"
  docker compose exec -T postgres psql -U sehat -d sehat_sahoolat <<'SQL'
    DO $$
    DECLARE r record;
    BEGIN
      FOR r IN (
        SELECT tablename FROM pg_tables
        WHERE schemaname='public' AND tablename NOT IN ('typeorm_migrations')
      ) LOOP
        EXECUTE format('TRUNCATE TABLE %I CASCADE', r.tablename);
      END LOOP;
    END $$;
SQL
fi

echo "[import] loading $(basename "$SNAPSHOT") ($(du -h "$SNAPSHOT" | cut -f1))…"
docker compose exec -T postgres psql -U sehat -d sehat_sahoolat < "$SNAPSHOT"

echo "[import] done"
echo ""
echo "Quick sanity check — table counts:"
docker compose exec -T postgres psql -U sehat -d sehat_sahoolat -c "
  SELECT 'users' AS t, COUNT(*)::text FROM users
  UNION ALL SELECT 'patients', COUNT(*)::text FROM patients
  UNION ALL SELECT 'doctors', COUNT(*)::text FROM doctors
  UNION ALL SELECT 'appointments', COUNT(*)::text FROM appointments
  UNION ALL SELECT 'packages', COUNT(*)::text FROM packages
  UNION ALL SELECT 'subscriptions', COUNT(*)::text FROM subscriptions
"
