#!/bin/bash
# DAK Zweitmeinungs-Portal — Deployment Script for Hetzner 1
# Run as root on the target server
set -euo pipefail

APP_DIR="/opt/dak-portal"
REPO_URL="https://github.com/complexcaresolutions/dak.c2s.git"
BRANCH="main"
SERVICE_USER="dak"

echo "=== DAK Portal Deployment ==="

# 1. Create service user if needed
if ! id "$SERVICE_USER" &>/dev/null; then
    echo "Creating service user '$SERVICE_USER'..."
    useradd --system --shell /bin/false --home-dir "$APP_DIR" "$SERVICE_USER"
fi

# 2. Clone or update repository
if [ -d "$APP_DIR/.git" ]; then
    echo "Updating existing installation..."
    cd "$APP_DIR"
    git fetch origin
    git checkout "$BRANCH"
    git pull origin "$BRANCH"
else
    echo "Fresh install — cloning repository..."
    git clone --branch "$BRANCH" "$REPO_URL" "$APP_DIR"
    cd "$APP_DIR"
fi

# 3. Backend setup
echo "Setting up backend..."
cd "$APP_DIR/backend"

if [ ! -d "venv" ]; then
    python3 -m venv venv
fi

source venv/bin/activate
pip install --quiet --upgrade pip
pip install --quiet -r requirements.txt

# 4. Create .env if it doesn't exist
if [ ! -f ".env" ]; then
    echo "Creating .env from template..."
    cat > .env << 'ENVEOF'
DB_HOST=localhost
DB_PORT=3306
DB_NAME=dak_c2s
DB_USER=dak_c2s_admin
DB_PASSWORD=CHANGE_ME

JWT_SECRET_KEY=CHANGE_ME_GENERATE_A_SECURE_KEY
JWT_ALGORITHM=HS256
ACCESS_TOKEN_EXPIRE_MINUTES=15
REFRESH_TOKEN_EXPIRE_DAYS=7

SMTP_HOST=smtp.complexcaresolutions.de
SMTP_PORT=465
SMTP_USER=noreply@complexcaresolutions.de
SMTP_PASSWORD=CHANGE_ME
SMTP_FROM=noreply@complexcaresolutions.de

APP_NAME=DAK Zweitmeinungs-Portal
CORS_ORIGINS=https://dak.complexcaresolutions.de
ENVEOF
    echo "!! IMPORTANT: Edit $APP_DIR/backend/.env with real credentials !!"
fi

# 5. Run database migrations
echo "Running Alembic migrations..."
alembic upgrade head

# 6. Frontend build
echo "Building frontend..."
cd "$APP_DIR/frontend"

if ! command -v pnpm &>/dev/null; then
    echo "Installing pnpm..."
    npm install -g pnpm
fi

pnpm install --frozen-lockfile
pnpm build

# 7. Set ownership
echo "Setting file ownership..."
chown -R "$SERVICE_USER":"$SERVICE_USER" "$APP_DIR"

# 8. Install systemd service
echo "Installing systemd service..."
cp "$APP_DIR/deploy/dak-backend.service" /etc/systemd/system/
systemctl daemon-reload
systemctl enable dak-backend
systemctl restart dak-backend

# 9. Install nginx config
echo "Installing nginx config..."
cp "$APP_DIR/deploy/dak-portal.nginx.conf" /etc/nginx/conf.d/dak-portal.conf
nginx -t && systemctl reload nginx

echo ""
echo "=== Deployment complete ==="
echo ""
echo "Next steps:"
echo "  1. Edit /opt/dak-portal/backend/.env with real DB password and JWT secret"
echo "  2. Create admin user: cd /opt/dak-portal/backend && source venv/bin/activate && python scripts/create_admin.py"
echo "  3. Check service: systemctl status dak-backend"
echo "  4. Check logs: journalctl -u dak-backend -f"
echo "  5. Test: curl https://dak.complexcaresolutions.de/api/health"
