#!/usr/bin/env bash
# Create Terraform Backend Storage Account
# This script creates the storage account for Terraform state if it doesn't exist

set -e

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
source "$SCRIPT_DIR/../lib/init.sh"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"
cd "$PROJECT_ROOT"
# Load .env via dotenv (RPC CR/LF trim). Fallback: raw source.
if [[ -f "$SCRIPT_DIR/../lib/deployment/dotenv.sh" ]]; then
  # shellcheck disable=SC1090
  source "$SCRIPT_DIR/../lib/deployment/dotenv.sh"
  load_deployment_env --repo-root "${PROJECT_ROOT:-$REPO_ROOT}"
elif [[ -n "${PROJECT_ROOT:-}" && -f "$PROJECT_ROOT/.env" ]]; then
  set -a
  # shellcheck disable=SC1090
  source "$PROJECT_ROOT/.env"
  set +a
elif [[ -n "${REPO_ROOT:-}" && -f "$REPO_ROOT/.env" ]]; then
  set -a
  # shellcheck disable=SC1090
  source "$REPO_ROOT/.env"
  set +a
fi


log_info "=== Creating Terraform Backend Storage Account ==="

if ! command -v az &> /dev/null; then
    log_warn "⚠️  Azure CLI not found"
    echo "Install Azure CLI: https://docs.microsoft.com/en-us/cli/azure/install-azure-cli"
    exit 1
fi

# Check authentication
if ! az account show &> /dev/null; then
    log_warn "⚠️  Not authenticated with Azure"
    echo "Run: az login"
    exit 1
fi

# Get subscription and location
SUBSCRIPTION_ID=$(az account show --query id -o tsv)
LOCATION="westeurope"
RESOURCE_GROUP="az-p-we-rg-tfstate-001"
STORAGE_ACCOUNT="azpwetfstate$(echo $SUBSCRIPTION_ID | cut -c1-8 | tr '[:upper:]' '[:lower:]')"
CONTAINER="tfstate"

echo "Configuration:"
echo "  Resource Group: $RESOURCE_GROUP"
echo "  Storage Account: $STORAGE_ACCOUNT"
echo "  Container: $CONTAINER"
echo "  Location: $LOCATION"

# Create resource group if it doesn't exist
if ! az group show --name "$RESOURCE_GROUP" &> /dev/null; then
    echo "Creating resource group..."
    az group create --name "$RESOURCE_GROUP" --location "$LOCATION" --output none
    log_success "✅ Resource group created"
else
    log_success "✅ Resource group exists"
fi

# Create storage account if it doesn't exist
if ! az storage account show --name "$STORAGE_ACCOUNT" --resource-group "$RESOURCE_GROUP" &> /dev/null; then
    echo "Creating storage account..."
    az storage account create \
        --name "$STORAGE_ACCOUNT" \
        --resource-group "$RESOURCE_GROUP" \
        --location "$LOCATION" \
        --sku Standard_LRS \
        --kind StorageV2 \
        --output none
    log_success "✅ Storage account created"
else
    log_success "✅ Storage account exists"
fi

# Get storage account key
STORAGE_KEY=$(az storage account keys list \
    --resource-group "$RESOURCE_GROUP" \
    --account-name "$STORAGE_ACCOUNT" \
    --query "[0].value" -o tsv)

# Create container if it doesn't exist
if ! az storage container show --name "$CONTAINER" --account-name "$STORAGE_ACCOUNT" --account-key "$STORAGE_KEY" &> /dev/null; then
    echo "Creating container..."
    az storage container create \
        --name "$CONTAINER" \
        --account-name "$STORAGE_ACCOUNT" \
        --account-key "$STORAGE_KEY" \
        --output none
    log_success "✅ Container created"
else
    log_success "✅ Container exists"
fi

# Update backend.tf or create .env entry
log_info "=== Backend Configuration ==="
echo "Add to .env file:"
echo "  ARM_STORAGE_ACCOUNT_NAME=$STORAGE_ACCOUNT"
echo "  ARM_CONTAINER_NAME=$CONTAINER"
echo "  ARM_RESOURCE_GROUP_NAME=$RESOURCE_GROUP"
echo "  ARM_ACCESS_KEY=$STORAGE_KEY"
echo "Or update terraform/backend.tf with:"
echo "  resource_group_name  = \"$RESOURCE_GROUP\"
echo "  storage_account_name = \"$STORAGE_ACCOUNT\"
echo "  container_name       = \"$CONTAINER\"
echo "  key                  = \"defi-oracle-mainnet.terraform.tfstate\"
log_success "✅ Backend storage account ready"
