#!/bin/bash

set -euo pipefail

# Configuration
PROJECT_ID="${PROJECT_ID:-accessible-video-platform}"
BUCKET_NAME="accessible-video-spa-${PROJECT_ID}"
API_URL="${API_URL:-}"

echo "🌐 Deploying SPA to Cloud Storage + Cloud CDN"
echo "Project: $PROJECT_ID"
echo "Bucket: $BUCKET_NAME"

# Validate environment
if ! command -v gcloud &> /dev/null; then
    echo "❌ gcloud CLI not found. Please install Google Cloud SDK."
    exit 1
fi

if ! command -v npm &> /dev/null; then
    echo "❌ npm not found. Please install Node.js."
    exit 1
fi

# Set project
echo "📋 Setting project to $PROJECT_ID"
gcloud config set project "$PROJECT_ID"

# Build frontend
echo "🏗️ Building frontend..."
cd "$(dirname "$0")/../../frontend"

# Install dependencies
npm ci

# Set build-time environment variables
if [ -n "$API_URL" ]; then
    echo "VITE_API_URL=$API_URL" > .env.production
    echo "VITE_ENVIRONMENT=production" >> .env.production
fi

# Build for production
npm run build

# Deploy to GCS
echo "📦 Deploying to GCS bucket: $BUCKET_NAME"

# Upload all files
gsutil -m rsync -r -d ./dist "gs://$BUCKET_NAME/"

# Set cache control headers
echo "⚡ Setting cache control headers..."

# Long cache for static assets (with content hash)
gsutil -m setmeta -h "Cache-Control:public, max-age=31536000, immutable" \
    "gs://$BUCKET_NAME/assets/**"

# No cache for HTML files
gsutil -m setmeta -h "Cache-Control:no-cache, no-store, must-revalidate" \
    -h "Pragma:no-cache" \
    -h "Expires:0" \
    "gs://$BUCKET_NAME/*.html"

# Short cache for other files
gsutil -m setmeta -h "Cache-Control:public, max-age=300" \
    "gs://$BUCKET_NAME/*.js" \
    "gs://$BUCKET_NAME/*.css" \
    "gs://$BUCKET_NAME/*.json" \
    "gs://$BUCKET_NAME/*.ico" || true

echo "✅ SPA deployment completed successfully!"
echo ""
echo "📍 Bucket URL: https://storage.googleapis.com/$BUCKET_NAME/index.html"
echo ""
echo "🔧 Next steps:"
echo "1. Configure Cloud CDN with Terraform: terraform apply in infra/cloud-cdn/"
echo "2. Point your domain DNS to the Load Balancer IP"
echo "3. Wait for SSL certificate provisioning (can take up to 60 minutes)"
echo "4. Test the application end-to-end"