#!/bin/bash
#
# Phase 5: Container Registry Setup
# Configure Azure Container Registry and attach to AKS
#

set -euo pipefail

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

log_info "=========================================="
log_info "Phase 5: Container Registry Setup"
log_info "=========================================="

# 5.1 Verify ACR exists
log_step "5.1 Verifying Azure Container Registry..."

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

if [ -z "${ACR_EXISTS}" ]; then
  log_warning "ACR ${ACR_NAME} not found"
  log_info "ACR should be created by Terraform"
  log_info "Skipping ACR configuration"
  exit 0
fi

log_success "ACR found: ${ACR_NAME}"

# 5.2 Configure ACR access
log_step "5.2 Configuring ACR access..."

# Enable admin user (or use managed identity)
az acr update --name "${ACR_NAME}" --admin-enabled true \
  || log_warning "Failed to enable admin user (may already be enabled)"

# 5.3 Attach ACR to AKS
log_step "5.3 Attaching ACR to AKS..."

az aks update \
  --name "${AKS_NAME}" \
  --resource-group "${AKS_RESOURCE_GROUP}" \
  --attach-acr "${ACR_NAME}" \
  || log_warning "Failed to attach ACR (may already be attached)"

log_success "ACR attached to AKS"

# 5.4 Test ACR access
log_step "5.4 Testing ACR access..."

az acr login --name "${ACR_NAME}" || error_exit "Failed to login to ACR"

log_success "ACR access verified"

# Save state
save_state "phase5" "complete"

log_success "=========================================="
log_success "Phase 5: Container Registry - COMPLETE"
log_success "=========================================="

