#!/bin/bash
#
# Phase 4: Database & Storage Setup
# Configure PostgreSQL, Storage Accounts, Redis, OpenSearch
#

set -euo pipefail

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

log_info "=========================================="
log_info "Phase 4: Database & Storage Setup"
log_info "=========================================="

# 4.1 PostgreSQL Database Setup
log_step "4.1 Configuring PostgreSQL database..."

# Check if database exists
DB_EXISTS=$(az postgres db show \
  --resource-group "${AKS_RESOURCE_GROUP}" \
  --server-name "${POSTGRES_SERVER_NAME}" \
  --name "${POSTGRES_DB_NAME}" \
  --query name -o tsv 2>/dev/null || echo "")

if [ -z "${DB_EXISTS}" ]; then
  log_info "Creating database ${POSTGRES_DB_NAME}..."
  az postgres db create \
    --resource-group "${AKS_RESOURCE_GROUP}" \
    --server-name "${POSTGRES_SERVER_NAME}" \
    --name "${POSTGRES_DB_NAME}" \
    || error_exit "Failed to create database"
  log_success "Database created"
else
  log_success "Database already exists"
fi

# Configure firewall rules for AKS
log_step "4.2 Configuring database firewall rules..."

# Get AKS outbound IPs (if using NAT gateway)
# For now, allow Azure services
az postgres server firewall-rule create \
  --resource-group "${AKS_RESOURCE_GROUP}" \
  --server-name "${POSTGRES_SERVER_NAME}" \
  --name "AllowAzureServices" \
  --start-ip-address "0.0.0.0" \
  --end-ip-address "0.0.0.0" \
  --output none 2>/dev/null || log_info "Firewall rule may already exist"

log_success "Database firewall configured"

# 4.2 Storage Account Setup
log_step "4.3 Configuring storage accounts..."

# Verify storage account exists
STORAGE_EXISTS=$(az storage account show \
  --name "${STORAGE_ACCOUNT_NAME}" \
  --resource-group "${AKS_RESOURCE_GROUP}" \
  --query name -o tsv 2>/dev/null || echo "")

if [ -z "${STORAGE_EXISTS}" ]; then
  log_warning "Storage account ${STORAGE_ACCOUNT_NAME} not found"
  log_info "Storage account should be created by Terraform"
else
  log_success "Storage account found"
  
  # Create containers
  CONTAINERS=("intake-documents" "dataroom-deals" "credentials")
  
  for container in "${CONTAINERS[@]}"; do
    log_info "Creating container: ${container}..."
    az storage container create \
      --name "${container}" \
      --account-name "${STORAGE_ACCOUNT_NAME}" \
      --auth-mode login \
      --output none 2>/dev/null && \
      log_success "Container ${container} created" || \
      log_info "Container ${container} may already exist"
  done
fi

# Save state
save_state "phase4" "complete"

log_success "=========================================="
log_success "Phase 4: Database & Storage - COMPLETE"
log_success "=========================================="

