#!/bin/bash
# Apply Consent History migration and rebuild backend-compliance on Mac Mini
# Usage: bash scripts/apply_consent_history_migration.sh

set -e

DOCKER="/usr/local/bin/docker"
BACKEND_CONTAINER="bp-compliance-backend"
PROJECT_DIR="/Users/benjaminadmin/Projekte/breakpilot-compliance"

echo "==> Pushing code to Mac Mini..."
git push origin main

echo "==> Pulling code on Mac Mini..."
ssh macmini "git -C ${PROJECT_DIR} pull --no-rebase origin main"

echo "==> Applying Consent History migration (009_consent_history.sql)..."
ssh macmini "${DOCKER} exec ${BACKEND_CONTAINER} \
    psql \"\${DATABASE_URL}\" -f /app/migrations/009_consent_history.sql \
    && echo 'Consent History migration applied' \
    || echo 'psql failed, trying python...'"

ssh macmini "${DOCKER} exec ${BACKEND_CONTAINER} \
    python3 -c \"
import psycopg2, os
conn = psycopg2.connect(os.environ['DATABASE_URL'])
conn.autocommit = True
cur = conn.cursor()
with open('/app/migrations/009_consent_history.sql', 'r') as f:
    sql = f.read()
cur.execute(sql)
cur.close()
conn.close()
print('Consent History migration (python) applied')
\"" 2>/dev/null || echo "Note: Migration already applied or use manual SQL."

echo ""
echo "==> Rebuilding backend-compliance..."
ssh macmini "${DOCKER} compose -f ${PROJECT_DIR}/docker-compose.yml build --no-cache backend-compliance && \
  ${DOCKER} compose -f ${PROJECT_DIR}/docker-compose.yml up -d backend-compliance"

echo ""
echo "==> Verifying history endpoint..."
sleep 5
curl -sk "https://macmini:8002/api/compliance/einwilligungen/consents/test/history" \
  -H "X-Tenant-ID: test-tenant" \
  | python3 -c "import sys,json; d=json.load(sys.stdin); print(f'History endpoint OK: {type(d).__name__}')" \
  || echo "Endpoint check needs backend restart"

echo ""
echo "Done. Check logs: ssh macmini '${DOCKER} logs -f ${BACKEND_CONTAINER}'"
