#!/usr/bin/env bash
# Configure Database - Run migrations and setup for DBIS Core

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/../../.." && pwd)"

# Source utilities
source "$PROJECT_ROOT/dbis_core/scripts/utils/common.sh"
source "$PROJECT_ROOT/dbis_core/scripts/utils/dbis-core-utils.sh" 2>/dev/null || true

# Load configuration
load_config

log_info "========================================="
log_info "DBIS Core - Database Configuration"
log_info "========================================="
log_info ""

check_root
if ! command_exists pct; then
    error_exit "This script must be run on Proxmox host (pct command not found)"
fi

VMID_POSTGRES="${VMID_DBIS_POSTGRES_PRIMARY:-10100}"
DB_HOST="${DBIS_POSTGRES_PRIMARY_IP:-192.168.11.100}"
DB_NAME="${DBIS_DB_NAME:-dbis_core}"
DB_USER="${DBIS_DB_USER:-dbis}"
DB_PASSWORD="${DBIS_DB_PASSWORD:-}"

if [[ -z "$DB_PASSWORD" ]]; then
    log_error "DBIS_DB_PASSWORD not set. Please set it in config or environment."
    exit 1
fi

log_info "Configuring database on container $VMID_POSTGRES..."

# Check if container is running
if ! pct list | grep -q "^\s*$VMID_POSTGRES\s"; then
    error_exit "PostgreSQL container $VMID_POSTGRES not found"
fi

# Wait for PostgreSQL to be ready
log_info "Waiting for PostgreSQL to be ready..."
sleep 5

# Run Prisma migrations
log_info "Running Prisma migrations..."

# Find API container to run migrations from
VMID_API="${VMID_DBIS_API_PRIMARY:-10150}"
if pct list | grep -q "^\s*$VMID_API\s"; then
    log_info "Running migrations from API container $VMID_API..."
    
    # Set DATABASE_URL in container
    pct exec "$VMID_API" -- bash -c "export DATABASE_URL=postgresql://${DB_USER}:${DB_PASSWORD}@${DB_HOST}:5432/${DB_NAME}"
    
    # Generate Prisma client
    log_info "Generating Prisma client..."
    pct exec "$VMID_API" -- bash -c "cd ${DBIS_CORE_PROJECT_ROOT:-/opt/dbis-core} && npx prisma generate" 2>&1 | grep -vE "(perl: warning|locale:)" || {
        log_error "Failed to generate Prisma client"
        exit 1
    }
    
    # Run migrations
    log_info "Running database migrations..."
    pct exec "$VMID_API" -- bash -c "cd ${DBIS_CORE_PROJECT_ROOT:-/opt/dbis-core} && npx prisma migrate deploy" 2>&1 | grep -vE "(perl: warning|locale:)" || {
        log_error "Failed to run migrations"
        exit 1
    }
    
    # Verify migration status
    log_info "Verifying migration status..."
    pct exec "$VMID_API" -- bash -c "cd ${DBIS_CORE_PROJECT_ROOT:-/opt/dbis-core} && npx prisma migrate status" 2>&1 | grep -vE "(perl: warning|locale:)" || true
    
    log_success "Database migrations completed!"
else
    log_warn "API container not found. Migrations will need to be run manually."
    log_info "To run migrations manually:"
    log_info "1. Connect to API container: pct enter $VMID_API"
    log_info "2. cd ${DBIS_CORE_PROJECT_ROOT:-/opt/dbis-core}"
    log_info "3. export DATABASE_URL=postgresql://${DB_USER}:${DB_PASSWORD}@${DB_HOST}:5432/${DB_NAME}"
    log_info "4. npx prisma migrate deploy"
fi

log_info ""
log_info "Database configuration completed!"

