#!/bin/bash

# Blazor App with Grafana Stack - Deployment Script

set -e

echo "==================================="
echo "Blazor Grafana Stack Deployment"
echo "==================================="

# Variables
LOCATION="eastus"
RESOURCE_GROUP="rg-blazor-grafana"
DEPLOYMENT_NAME="blazor-deployment-$(date +%Y%m%d-%H%M%S)"

# Check if Azure CLI is installed
if ! command -v az &> /dev/null; then
    echo "Error: Azure CLI is not installed. Please install it first."
    exit 1
fi

# Check if logged in
echo "Checking Azure login status..."
az account show > /dev/null 2>&1 || { echo "Please login to Azure first: az login"; exit 1; }

# Deploy the infrastructure
echo ""
echo "Deploying infrastructure to Azure..."
echo "Location: $LOCATION"
echo "Deployment Name: $DEPLOYMENT_NAME"
echo ""

az deployment sub create \
    --name "$DEPLOYMENT_NAME" \
    --location "$LOCATION" \
    --template-file ./.bicep/main.bicep \
    --parameters resourceGroupName="$RESOURCE_GROUP" location="$LOCATION" \
    --output table

# Get outputs
echo ""
echo "Retrieving deployment outputs..."
WEBAPP_NAME=$(az deployment sub show --name "$DEPLOYMENT_NAME" --query properties.outputs.webAppName.value -o tsv)
WEBAPP_URL=$(az deployment sub show --name "$DEPLOYMENT_NAME" --query properties.outputs.webAppUrl.value -o tsv)

echo ""
echo "==================================="
echo "Deployment Complete!"
echo "==================================="
echo "Resource Group: $RESOURCE_GROUP"
echo "Web App Name: $WEBAPP_NAME"
echo "Web App URL: $WEBAPP_URL"
echo ""
echo "Next Steps:"
echo "1. Build and publish your Blazor app:"
echo "   cd BlazorApp"
echo "   dotnet publish -c Release -o ./publish"
echo ""
echo "2. Deploy to Azure:"
echo "   cd publish"
echo "   zip -r app.zip ."
echo "   az webapp deployment source config-zip --resource-group $RESOURCE_GROUP --name $WEBAPP_NAME --src app.zip"
echo ""
echo "3. Access metrics at: $WEBAPP_URL/metrics"
echo "4. Access health check at: $WEBAPP_URL/health"
echo ""
echo "==================================="
