#!/usr/bin/env bash
# Deploy till befintlig server (spec §51, steg 1).
# Körs som den dedikerade app-användaren på servern.
set -euo pipefail

APP_DIR="/opt/${APP_SLUG:-app}-platform"
REPO_DIR="$APP_DIR/repo"
COMPOSE="$REPO_DIR/infrastructure/docker/docker-compose.production.yml"

echo "==> Deploy $(date -Iseconds)"

cd "$REPO_DIR"
git fetch --tags origin main
PREV_SHA=$(git rev-parse HEAD)
git reset --hard origin/main
NEW_SHA=$(git rev-parse HEAD)
echo "==> $PREV_SHA -> $NEW_SHA"

echo "==> Bygger images"
docker compose -f "$COMPOSE" build

echo "==> Kör databas-migrationer (med backup-punkt först)"
# RDS: automatiska snapshots finns; ta även logisk dump för snabb rollback.
mkdir -p "$APP_DIR/backups"
pg_dump "$DATABASE_URL" --format=custom \
  --file="$APP_DIR/backups/pre-deploy-$(date +%Y%m%d-%H%M%S).dump" || {
    echo "VARNING: pg_dump misslyckades – avbryter deploy (spec §63: ingen migration utan backup)"; exit 1;
  }
docker run --rm --env-file "$APP_DIR/secrets/api.env" app-api:latest \
  node dist/index.js --migrate-only 2>/dev/null || true
# Migrationer körs normalt från CI/lokalt: pnpm db:migrate mot produktion via bastion.

echo "==> Startar om tjänster (rullande)"
docker compose -f "$COMPOSE" up -d app-redis
docker compose -f "$COMPOSE" up -d app-worker
docker compose -f "$COMPOSE" up -d app-api
docker compose -f "$COMPOSE" up -d app-admin

echo "==> Healthcheck"
sleep 5
if ! curl -fsS http://127.0.0.1:4100/healthz > /dev/null; then
  echo "FEL: API svarar inte – rollback till $PREV_SHA"
  git reset --hard "$PREV_SHA"
  docker compose -f "$COMPOSE" build app-api
  docker compose -f "$COMPOSE" up -d app-api
  exit 1
fi

echo "==> Deploy klar: $NEW_SHA"
