#!/bin/bash
#
# Phase 6: Application Build & Package
# Build applications and create Docker images
#

set -euo pipefail

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

log_info "=========================================="
log_info "Phase 6: Application Build & Package"
log_info "=========================================="

cd "${PROJECT_ROOT}"

# 6.1 Build Packages
log_step "6.1 Building shared packages..."

if [ "${SKIP_BUILD:-false}" != "true" ]; then
  log_info "Building all packages..."
  pnpm build || error_exit "Failed to build packages"
  log_success "All packages built"
else
  log_info "Skipping build (SKIP_BUILD=true)"
fi

# 6.2 Build Frontend Applications
log_step "6.2 Building frontend applications..."

for app in "${APPS[@]}"; do
  log_info "Building ${app}..."
  pnpm --filter "${app}" build || log_warning "Failed to build ${app}"
done

log_success "Frontend applications built"

# 6.3 Build Backend Services
log_step "6.3 Building backend services..."

for service in "${SERVICES[@]}"; do
  log_info "Building ${service}..."
  pnpm --filter "@the-order/${service}" build || log_warning "Failed to build ${service}"
done

log_success "Backend services built"

# 6.4 Create Docker Images
log_step "6.4 Creating Docker images..."

# Check if Docker is running
if ! docker info &> /dev/null; then
  error_exit "Docker is not running"
fi

# Login to ACR
log_info "Logging into Azure Container Registry..."
az acr login --name "${ACR_NAME}" || error_exit "Failed to login to ACR"

# Build and push service images
for service in "${SERVICES[@]}"; do
  DOCKERFILE="${PROJECT_ROOT}/services/${service}/Dockerfile"
  
  if [ ! -f "${DOCKERFILE}" ]; then
    log_warning "Dockerfile not found for ${service}: ${DOCKERFILE}"
    log_info "Skipping ${service} image build"
    continue
  fi
  
  IMAGE_NAME="${ACR_NAME}.azurecr.io/${service}:${IMAGE_TAG}"
  IMAGE_NAME_SHA="${ACR_NAME}.azurecr.io/${service}:$(git rev-parse --short HEAD 2>/dev/null || echo 'latest')"
  
  log_info "Building ${service} image..."
  docker build -t "${IMAGE_NAME}" \
               -t "${IMAGE_NAME_SHA}" \
               -f "${DOCKERFILE}" \
               "${PROJECT_ROOT}" || error_exit "Failed to build ${service} image"
  
  log_info "Pushing ${service} image..."
  docker push "${IMAGE_NAME}" || error_exit "Failed to push ${service} image"
  docker push "${IMAGE_NAME_SHA}" || log_warning "Failed to push ${service} SHA image"
  
  log_success "${service} image built and pushed"
done

# Build and push app images
for app in "${APPS[@]}"; do
  DOCKERFILE="${PROJECT_ROOT}/apps/${app}/Dockerfile"
  
  if [ ! -f "${DOCKERFILE}" ]; then
    log_warning "Dockerfile not found for ${app}: ${DOCKERFILE}"
    log_info "Skipping ${app} image build"
    continue
  fi
  
  IMAGE_NAME="${ACR_NAME}.azurecr.io/${app}:${IMAGE_TAG}"
  IMAGE_NAME_SHA="${ACR_NAME}.azurecr.io/${app}:$(git rev-parse --short HEAD 2>/dev/null || echo 'latest')"
  
  log_info "Building ${app} image..."
  docker build -t "${IMAGE_NAME}" \
               -t "${IMAGE_NAME_SHA}" \
               -f "${DOCKERFILE}" \
               "${PROJECT_ROOT}" || error_exit "Failed to build ${app} image"
  
  log_info "Pushing ${app} image..."
  docker push "${IMAGE_NAME}" || error_exit "Failed to push ${app} image"
  docker push "${IMAGE_NAME_SHA}" || log_warning "Failed to push ${app} SHA image"
  
  log_success "${app} image built and pushed"
done

# Sign images with Cosign (if available)
if command -v cosign &> /dev/null; then
  log_step "6.5 Signing images with Cosign..."
  
  for service in "${SERVICES[@]}"; do
    IMAGE_NAME="${ACR_NAME}.azurecr.io/${service}:${IMAGE_TAG}"
    log_info "Signing ${service} image..."
    cosign sign --yes "${IMAGE_NAME}" || log_warning "Failed to sign ${service} image"
  done
  
  for app in "${APPS[@]}"; do
    IMAGE_NAME="${ACR_NAME}.azurecr.io/${app}:${IMAGE_TAG}"
    log_info "Signing ${app} image..."
    cosign sign --yes "${IMAGE_NAME}" || log_warning "Failed to sign ${app} image"
  done
  
  log_success "Images signed"
else
  log_warning "Cosign not found, skipping image signing"
fi

# Save state
save_state "phase6" "complete"

log_success "=========================================="
log_success "Phase 6: Build & Package - COMPLETE"
log_success "=========================================="

