#!/bin/bash
#
# Phase 8: Secrets Configuration
# Store secrets in Azure Key Vault
# Note: Some secrets may need to be set manually
#

set -euo pipefail

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

log_info "=========================================="
log_info "Phase 8: Secrets Configuration"
log_info "=========================================="

# Verify Key Vault exists
log_step "8.1 Verifying Azure Key Vault..."

KV_EXISTS=$(az keyvault show \
  --name "${KEY_VAULT_NAME}" \
  --resource-group "${AKS_RESOURCE_GROUP}" \
  --query name -o tsv 2>/dev/null || echo "")

if [ -z "${KV_EXISTS}" ]; then
  error_exit "Key Vault ${KEY_VAULT_NAME} not found. Create it first with Terraform."
fi

log_success "Key Vault found: ${KEY_VAULT_NAME}"

# Store database URL if provided
if [ -n "${DATABASE_URL:-}" ]; then
  log_step "8.2 Storing database URL..."
  az keyvault secret set \
    --vault-name "${KEY_VAULT_NAME}" \
    --name "database-url-${ENVIRONMENT}" \
    --value "${DATABASE_URL}" \
    || log_warning "Failed to store database URL"
  log_success "Database URL stored"
fi

# Check for Entra secrets
log_step "8.3 Checking Entra ID secrets..."

ENTRA_SECRETS=("entra-tenant-id" "entra-client-id" "entra-client-secret" "entra-credential-manifest-id")
MISSING_SECRETS=()

for secret in "${ENTRA_SECRETS[@]}"; do
  if ! az keyvault secret show \
    --vault-name "${KEY_VAULT_NAME}" \
    --name "${secret}" \
    --query value -o tsv &> /dev/null; then
    MISSING_SECRETS+=("${secret}")
  fi
done

if [ ${#MISSING_SECRETS[@]} -gt 0 ]; then
  log_warning "Missing Entra ID secrets: ${MISSING_SECRETS[*]}"
  log_info "Run: ./scripts/deploy/store-entra-secrets.sh"
else
  log_success "All Entra ID secrets found"
fi

# Store JWT secret if not exists
log_step "8.4 Storing JWT secret..."

if ! az keyvault secret show \
  --vault-name "${KEY_VAULT_NAME}" \
  --name "jwt-secret" \
  --query value -o tsv &> /dev/null; then
  
  JWT_SECRET=$(openssl rand -base64 32)
  az keyvault secret set \
    --vault-name "${KEY_VAULT_NAME}" \
    --name "jwt-secret" \
    --value "${JWT_SECRET}" \
    || error_exit "Failed to store JWT secret"
  log_success "JWT secret generated and stored"
else
  log_success "JWT secret already exists"
fi

log_info "Secrets configuration complete"
log_info "Note: Additional secrets may need to be set manually"
log_info "See docs/deployment/DEPLOYMENT_GUIDE.md Phase 8 for complete list"

# Save state
save_state "phase8" "complete"

log_success "=========================================="
log_success "Phase 8: Secrets Configuration - COMPLETE"
log_success "=========================================="

