#!/usr/bin/env bash
# Run database migrations for Sankofa on r630-01

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
SANKOFA_PROJECT="${SANKOFA_PROJECT:-/home/intlc/projects/Sankofa}"
source "$SCRIPT_DIR/env.r630-01.example" 2>/dev/null || true

# Colors
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m'

log_info() { echo -e "${BLUE}[INFO]${NC} $1"; }
log_success() { echo -e "${GREEN}[✓]${NC} $1"; }
log_warn() { echo -e "${YELLOW}[WARN]${NC} $1"; }
log_error() { echo -e "${RED}[ERROR]${NC} $1"; }

# Configuration
PROXMOX_HOST="${PROXMOX_HOST:-192.168.11.11}"
VMID_API="${VMID_SANKOFA_API:-7800}"
DB_HOST="${DB_HOST:-10.160.0.13}"
DB_PORT="${DB_PORT:-5432}"
DB_NAME="${DB_NAME:-sankofa}"
DB_USER="${DB_USER:-sankofa}"
DB_PASSWORD="${DB_PASSWORD:-}"

# SSH function
ssh_r630_01() {
    ssh -o StrictHostKeyChecking=no -o ConnectTimeout=5 root@"$PROXMOX_HOST" "$@"
}

main() {
    echo ""
    log_info "========================================="
    log_info "Running Database Migrations"
    log_info "========================================="
    echo ""
    
    if [[ -z "$DB_PASSWORD" ]]; then
        log_error "DB_PASSWORD not set. Please update env.r630-01.example or set DB_PASSWORD environment variable."
        exit 1
    fi
    
    log_info "Connecting to API container (VMID: $VMID_API)..."
    
    # Run migrations
    ssh_r630_01 "pct exec $VMID_API -- bash -c 'cd /opt/sankofa-api && \
        DB_HOST=$DB_HOST \
        DB_PORT=$DB_PORT \
        DB_NAME=$DB_NAME \
        DB_USER=$DB_USER \
        DB_PASSWORD=\"$DB_PASSWORD\" \
        pnpm db:migrate'"
    
    log_success "Migrations completed"
    echo ""
}

main "$@"
