#!/bin/bash
#
# Phase 7: Database Migrations
# Run database schema migrations
#

set -euo pipefail

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

log_info "=========================================="
log_info "Phase 7: Database Migrations"
log_info "=========================================="

cd "${PROJECT_ROOT}"

# Get database URL from Key Vault or environment
if [ -z "${DATABASE_URL:-}" ]; then
  log_info "Retrieving DATABASE_URL from Azure Key Vault..."
  DATABASE_URL=$(az keyvault secret show \
    --vault-name "${KEY_VAULT_NAME}" \
    --name "database-url-${ENVIRONMENT}" \
    --query value -o tsv 2>/dev/null || echo "")
  
  if [ -z "${DATABASE_URL}" ]; then
    error_exit "DATABASE_URL not found in Key Vault and not set in environment"
  fi
fi

log_step "7.1 Running database migrations for ${ENVIRONMENT}..."

# Export DATABASE_URL for migration script
export DATABASE_URL

# Run migrations
log_info "Running migrations..."
pnpm --filter @the-order/database migrate up || error_exit "Database migrations failed"

log_success "Database migrations completed"

# Verify schema
log_step "7.2 Verifying database schema..."

# Check if we can connect and list tables
if command -v psql &> /dev/null; then
  # Extract connection details from DATABASE_URL
  # Format: postgresql://user:pass@host:port/database
  DB_CONN=$(echo "${DATABASE_URL}" | sed 's|postgresql://||')
  DB_USER=$(echo "${DB_CONN}" | cut -d':' -f1)
  DB_PASS=$(echo "${DB_CONN}" | cut -d':' -f2 | cut -d'@' -f1)
  DB_HOST=$(echo "${DB_CONN}" | cut -d'@' -f2 | cut -d':' -f1)
  DB_PORT=$(echo "${DB_CONN}" | cut -d':' -f3 | cut -d'/' -f1)
  DB_NAME=$(echo "${DB_CONN}" | cut -d'/' -f2)
  
  log_info "Verifying connection to ${DB_HOST}:${DB_PORT}/${DB_NAME}..."
  PGPASSWORD="${DB_PASS}" psql -h "${DB_HOST}" -p "${DB_PORT}" -U "${DB_USER}" -d "${DB_NAME}" -c "\dt" &> /dev/null && \
    log_success "Database connection verified" || \
    log_warning "Could not verify database connection with psql"
else
  log_warning "psql not found, skipping schema verification"
fi

# Save state
save_state "phase7" "complete"

log_success "=========================================="
log_success "Phase 7: Database Migrations - COMPLETE"
log_success "=========================================="

