#!/bin/bash

# setup-local-env.sh
# Fetches Firebase configuration from Terraform outputs and creates a local .env file.

# Check if terraform is installed
if ! command -v terraform &> /dev/null; then
  echo "❌ Error: terraform is not installed or not in PATH."
  exit 1
fi

# Check if jq is installed
if ! command -v jq &> /dev/null; then
  echo "❌ Error: jq is not installed. Please install jq to parse JSON output."
  exit 1
fi

TERRAFORM_DIR="terraform"
ENV_FILE=".env"

echo "🔍 Fetching Firebase configuration from Terraform..."

if [ ! -d "$TERRAFORM_DIR" ]; then
  echo "❌ Error: Terraform directory '$TERRAFORM_DIR' not found."
  exit 1
fi

cd "$TERRAFORM_DIR" || exit

# Check if Terraform is initialized
if [ ! -d ".terraform" ]; then
    echo "⚠️ Terraform not initialized. Initializing..."
    terraform init
fi

# Fetch output in JSON format
TF_OUT=$(terraform output -json firebase_config 2>/dev/null)
cd ..

if [ -z "$TF_OUT" ]; then
  echo "❌ Error: Could not fetch 'firebase_config' from Terraform output."
  echo "   Ensure 'terraform apply' has been run successfully."
  exit 1
fi

echo "📝 Writing to $ENV_FILE..."

# Parse JSON and write to .env
# We use a heredoc to write the file content
cat > "$ENV_FILE" <<EOF
VITE_FIREBASE_API_KEY=$(echo $TF_OUT | jq -r .apiKey)
VITE_FIREBASE_AUTH_DOMAIN=$(echo $TF_OUT | jq -r .authDomain)
VITE_FIREBASE_PROJECT_ID=$(echo $TF_OUT | jq -r .projectId)
VITE_FIREBASE_STORAGE_BUCKET=$(echo $TF_OUT | jq -r .storageBucket)
VITE_FIREBASE_MESSAGING_SENDER_ID=$(echo $TF_OUT | jq -r .messagingSenderId)
VITE_FIREBASE_APP_ID=$(echo $TF_OUT | jq -r .appId)
EOF

echo "✅ Success! .env file created."
cat "$ENV_FILE"
