#!/usr/bin/env bash
set -Eeuo pipefail

trap 'echo "[reset][ERROR] Rad ${LINENO}: kommando misslyckades: ${BASH_COMMAND}" >&2' ERR

# ----------------------------------------
# Config
# ----------------------------------------
APP_DIR="${1:-/opt/containers/recipe-app}"
COMPOSE_FILES=(-f compose.yml -f compose.flutter.yml)
DB_CONTAINER="recipe-db"
IMPORTER_DIR="../microservice-importer"
SEED_FILE="db/seeds/seed_all.sql"

# ----------------------------------------
# Helpers
# ----------------------------------------
log() { echo "[reset] $*"; }
fail() { echo "[reset][ERROR] $*" >&2; exit 1; }

require_cmd() {
  command -v "$1" >/dev/null 2>&1 || fail "Saknar kommando: $1"
}

require_docker_compose() {
  docker compose version >/dev/null 2>&1 || fail "docker compose saknas eller fungerar inte"
}

# ----------------------------------------
# Preflight
# ----------------------------------------
require_cmd docker
require_cmd git
require_cmd grep
require_cmd cut
require_cmd tr
require_docker_compose

cd "$APP_DIR" || fail "Kunde inte byta till katalog: $APP_DIR"

[ -f ".env" ] || fail ".env saknas i $APP_DIR"
[ -f "compose.yml" ] || fail "compose.yml saknas"
[ -f "compose.flutter.yml" ] || fail "compose.flutter.yml saknas"
[ -f "$SEED_FILE" ] || fail "$SEED_FILE saknas"

# Läs DB-variabler från .env (samma stil som manuella seed-kommandon)
DB_PASS="$(grep '^MARIADB_ROOT_PASSWORD=' .env | cut -d '=' -f2 | tr -d '"' | tr -d "'")"
DB_NAME="$(grep '^MARIADB_DATABASE=' .env | cut -d '=' -f2 | tr -d '"' | tr -d "'")"

[ -n "${DB_PASS:-}" ] || fail "MARIADB_ROOT_PASSWORD är tom i .env"
[ -n "${DB_NAME:-}" ] || fail "MARIADB_DATABASE är tom i .env"

echo
echo "VARNING: Detta gör en full reset av databasen."
echo "All data i DB-volymen försvinner (användare, inventarie, pantry, historik)."
echo
read -r -p "Fortsätt? Skriv JA för att bekräfta: " CONFIRM
[ "$CONFIRM" = "JA" ] || fail "Avbrutet av användare"

read -r -p "Vill du bygga om images också? (j/N): " BUILD_CONFIRM
if [[ "$BUILD_CONFIRM" =~ ^[JjYy]$ ]]; then
  RUN_BUILD=1
else
  RUN_BUILD=0
fi

# ----------------------------------------
# Pull latest code
# ----------------------------------------
if [ "${SKIP_GIT_PULL:-0}" = "1" ]; then
  log "SKIP_GIT_PULL=1 -> hoppar över git pull"
else
  log "Hämtar senaste kod för recipe-app"
  git pull origin main

  if [ -d "$IMPORTER_DIR/.git" ]; then
    log "Hämtar senaste kod för microservice-importer"
    (cd "$IMPORTER_DIR" && git pull origin main)
  else
    log "Importer-repot hittades inte i $IMPORTER_DIR -> hoppar över importer git pull"
  fi
fi

# ----------------------------------------
# Full reset + start
# ----------------------------------------
log "Stoppar stacken och tar bort volymer"
docker compose "${COMPOSE_FILES[@]}" down -v --remove-orphans

if [ "$RUN_BUILD" = "1" ]; then
  log "Bygger och startar stacken igen"
  docker compose "${COMPOSE_FILES[@]}" up -d --build
else
  log "Startar stacken utan build"
  docker compose "${COMPOSE_FILES[@]}" up -d
fi

# ----------------------------------------
# Wait for DB
# ----------------------------------------
log "Väntar på databasen"
for i in $(seq 1 60); do
  if docker exec "$DB_CONTAINER" mariadb-admin ping -h 127.0.0.1 -uroot -p"$DB_PASS" --silent >/dev/null 2>&1; then
    log "Databasen är redo"
    break
  fi
  if [ "$i" -eq 60 ]; then
    fail "Databasen blev inte redo i tid"
  fi
  sleep 2
done

# ----------------------------------------
# Run full seed
# ----------------------------------------
log "Kör full seed från $SEED_FILE"
docker exec -i "$DB_CONTAINER" mariadb -uroot -p"$DB_PASS" "$DB_NAME" < "$SEED_FILE"

# ----------------------------------------
# Post-checks
# ----------------------------------------
log "Visar container-status"
docker compose "${COMPOSE_FILES[@]}" ps

log "Kontrollerar kategori-kopplingar på produkter"
docker exec -i "$DB_CONTAINER" mariadb -uroot -p"$DB_PASS" "$DB_NAME" -e "
SELECT COUNT(*) AS total_products FROM Product;
SELECT COUNT(*) AS products_with_category FROM Product WHERE categoryId IS NOT NULL;
SELECT COUNT(*) AS products_without_category FROM Product WHERE categoryId IS NULL;
"

log "Klart"
