#!/usr/bin/env bash
set -euo pipefail

# Import all existing resource groups that match the multi-region naming pattern
# This script imports RGs that already exist in Azure but aren't in Terraform state

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"
TERRAFORM_DIR="$PROJECT_ROOT/terraform"

cd "$TERRAFORM_DIR"

# Map of region names to their 3-character codes
declare -A REGION_CODES=(
  ["southeastasia"]="sea"
  ["uaenorth"]="uan"
  ["germanywestcentral"]="gwc"
  ["israelcentral"]="ilc"
  ["norwayeast"]="noe"
  ["southafricanorth"]="san"
  ["chilecentral"]="chc"
  ["swedencentral"]="swc"
  ["ukwest"]="ukw"
  ["uksouth"]="uks"
)

SUBSCRIPTION_ID="fc08d829-4f14-413d-ab27-ce024425db0b"

echo "Importing existing resource groups into Terraform state..."
echo

for region in "${!REGION_CODES[@]}"; do
  code="${REGION_CODES[$region]}"
  rg_name="az-p-${code}-rg-comp-001"
  rg_id="/subscriptions/${SUBSCRIPTION_ID}/resourceGroups/${rg_name}"
  
  echo "Importing ${region} (${rg_name})..."
  
  if terraform import -lock-timeout=5m "azurerm_resource_group.global_multi_region[\"${region}\"]" "${rg_id}" 2>&1 | grep -q "Import prepared"; then
    echo "  ✅ Successfully imported ${region}"
  else
    echo "  ⚠️  ${region} may already be in state or import failed (check output above)"
  fi
  echo
done

echo "Import complete. Run 'terraform plan' to verify state."

