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

PROJECT_NAME=${PROJECT_NAME:-atproto-blog}
BUCKET_NAME=${BUCKET_NAME:-$PROJECT_NAME}
AWS_REGION=${AWS_REGION:-us-east-1}
AWS_PROFILE=${AWS_PROFILE:-default}
DYNAMODB_TABLE=${DYNAMODB_TABLE:-blogs}
API_DID=${API_DID:?'API_DID must be set (e.g. did:web:yourdomain.com)'}
IFRAMELY_API_KEY=${IFRAMELY_API_KEY:?'IFRAMELY_API_KEY must be set'}

ARTIFACTS_BUCKET_NAME=${ARTIFACTS_BUCKET_NAME:-$PROJECT_NAME-artifacts}
CLOUDFRONT_STACK_NAME=${CLOUDFRONT_STACK_NAME:-$PROJECT_NAME-cloudfront-stack}

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"

# ── Infrastructure ────────────────────────────────────────────────────────────

echo ""
echo "🗄️  Creating AWS DynamoDB tables..."
aws cloudformation deploy --profile "$AWS_PROFILE" --region "$AWS_REGION" \
  --template-file "$SCRIPT_DIR/cf/dynamodb.yaml" \
  --stack-name "$PROJECT_NAME-dynamodb-stack" \
  --no-fail-on-empty-changeset

echo ""
echo "🪣  Creating AWS S3 bucket..."
aws cloudformation deploy --profile "$AWS_PROFILE" --region "$AWS_REGION" \
  --template-file "$SCRIPT_DIR/cf/s3.yaml" \
  --stack-name "$PROJECT_NAME-s3-stack" \
  --parameter-overrides BucketName="$BUCKET_NAME" \
  --no-fail-on-empty-changeset

echo ""
echo "📦 Creating AWS artifacts bucket..."
aws cloudformation deploy --profile "$AWS_PROFILE" --region "$AWS_REGION" \
  --template-file "$SCRIPT_DIR/cf/artifacts.yaml" \
  --stack-name "$PROJECT_NAME-artifacts-stack" \
  --parameter-overrides ArtifactsBucketName="$ARTIFACTS_BUCKET_NAME" \
  --no-fail-on-empty-changeset

echo ""
echo "🔑 Creating AWS secrets stack..."
aws cloudformation deploy --profile "$AWS_PROFILE" --region "$AWS_REGION" \
  --template-file "$SCRIPT_DIR/cf/secrets.yaml" \
  --stack-name "$PROJECT_NAME-secrets-stack" \
  --no-fail-on-empty-changeset

IFRAMELY_SECRET_ARN=$(aws cloudformation describe-stacks --profile "$AWS_PROFILE" --region "$AWS_REGION" \
  --stack-name "${PROJECT_NAME}-secrets-stack" \
  --query 'Stacks[0].Outputs[?OutputKey==`IframelySecretArn`].OutputValue' \
  --output text)
CURRENT_KEY=$(aws secretsmanager get-secret-value --profile "$AWS_PROFILE" --region "$AWS_REGION" \
  --secret-id "$IFRAMELY_SECRET_ARN" \
  --query 'SecretString' --output text 2>/dev/null || echo '')
if [ "$CURRENT_KEY" != "$IFRAMELY_API_KEY" ]; then
  echo "🔑 Writing Iframely API key to secret..."
  aws secretsmanager put-secret-value --profile "$AWS_PROFILE" --region "$AWS_REGION" \
    --secret-id "$IFRAMELY_SECRET_ARN" \
    --secret-string "$IFRAMELY_API_KEY"
else
  echo "🔑 Iframely API key unchanged — skipping"
fi

echo ""
# Look up the existing CloudFront site URL so AllowedOrigin is correct on both
# first run and re-runs. Falls back to '*' only when the stack doesn't exist yet.
CLOUDFRONT_SITE_URL=$(aws cloudformation describe-stacks --profile "$AWS_PROFILE" --region "$AWS_REGION" \
  --stack-name "$CLOUDFRONT_STACK_NAME" \
  --query 'Stacks[0].Outputs[?OutputKey==`SiteUrl`].OutputValue' \
  --output text 2>/dev/null || echo '*')
CLOUDFRONT_SITE_URL=${CLOUDFRONT_SITE_URL:-*}

echo "🔐 Creating AWS blog API stack (V1 REST API)..."
aws cloudformation deploy --profile "$AWS_PROFILE" --region "$AWS_REGION" \
  --template-file "$SCRIPT_DIR/cf/blog-api.yaml" \
  --stack-name "$PROJECT_NAME-api-stack" \
  --capabilities CAPABILITY_NAMED_IAM \
  --no-fail-on-empty-changeset \
  --parameter-overrides ApiDid="$API_DID" DynamoDBTable="$DYNAMODB_TABLE" AllowedOrigin="$CLOUDFRONT_SITE_URL" IframelySecretArn="$IFRAMELY_SECRET_ARN"

API_GATEWAY_ID=$(aws cloudformation describe-stacks --profile "$AWS_PROFILE" --region "$AWS_REGION" \
  --stack-name "${PROJECT_NAME}-api-stack" \
  --query 'Stacks[0].Outputs[?OutputKey==`ApiId`].OutputValue' \
  --output text)

echo ""
echo "🛡️  Deploying WAFv2 WebACL (us-east-1)..."
aws cloudformation deploy --profile "$AWS_PROFILE" --region us-east-1 \
  --template-file "$SCRIPT_DIR/cf/waf.yaml" \
  --stack-name "$PROJECT_NAME-waf-stack" \
  --no-fail-on-empty-changeset

WEB_ACL_ARN=$(aws cloudformation describe-stacks --profile "$AWS_PROFILE" --region us-east-1 \
  --stack-name "$PROJECT_NAME-waf-stack" \
  --query 'Stacks[0].Outputs[?OutputKey==`WebACLArn`].OutputValue' \
  --output text)

echo ""
echo "🌐 Creating CloudFront distributions..."
aws cloudformation deploy --profile "$AWS_PROFILE" --region "$AWS_REGION" \
  --template-file "$SCRIPT_DIR/cf/cloudfront.yaml" \
  --stack-name "$CLOUDFRONT_STACK_NAME" \
  --no-fail-on-empty-changeset \
  --parameter-overrides \
    SiteBucketName="$BUCKET_NAME" \
    ApiGatewayId="$API_GATEWAY_ID" \
    WebACLArn="$WEB_ACL_ARN"

CLOUDFRONT_SITE_URL=$(aws cloudformation describe-stacks --profile "$AWS_PROFILE" --region "$AWS_REGION" \
  --stack-name "$CLOUDFRONT_STACK_NAME" \
  --query 'Stacks[0].Outputs[?OutputKey==`SiteUrl`].OutputValue' \
  --output text)

CLOUDFRONT_API_URL=$(aws cloudformation describe-stacks --profile "$AWS_PROFILE" --region "$AWS_REGION" \
  --stack-name "$CLOUDFRONT_STACK_NAME" \
  --query 'Stacks[0].Outputs[?OutputKey==`ApiUrl`].OutputValue' \
  --output text)

echo ""
echo "🔐 Updating blog API stack with CloudFront AllowedOrigin (${CLOUDFRONT_SITE_URL})..."
aws cloudformation deploy --profile "$AWS_PROFILE" --region "$AWS_REGION" \
  --template-file "$SCRIPT_DIR/cf/blog-api.yaml" \
  --stack-name "$PROJECT_NAME-api-stack" \
  --capabilities CAPABILITY_NAMED_IAM \
  --no-fail-on-empty-changeset \
  --parameter-overrides ApiDid="$API_DID" DynamoDBTable="$DYNAMODB_TABLE" AllowedOrigin="$CLOUDFRONT_SITE_URL" IframelySecretArn="$IFRAMELY_SECRET_ARN"

# ── Lambda ────────────────────────────────────────────────────────────────────

echo ""
echo "🔧 Building and deploying blog API lambda..."
make -C "$SCRIPT_DIR" install-lambda
make -C "$SCRIPT_DIR" update-aws-api

# ── Backfill ──────────────────────────────────────────────────────────────────

echo ""
echo "🖥️  Building and deploying backfill Lambda..."
make -C "$SCRIPT_DIR" deploy-aws-backfill ARTIFACTS_BUCKET_NAME="$ARTIFACTS_BUCKET_NAME"

# ── Indexer ───────────────────────────────────────────────────────────────────

echo ""
echo "🖥️  Building and deploying indexer..."
make -C "$SCRIPT_DIR" deploy-aws-indexer ARTIFACTS_BUCKET_NAME="$ARTIFACTS_BUCKET_NAME"

# ── Frontend ──────────────────────────────────────────────────────────────────

{
  echo "VITE_API_URL=${CLOUDFRONT_API_URL}"
  echo "VITE_API_DID=${API_DID}"
} > "$SCRIPT_DIR/../.env.local"
echo "✅ Wrote .env.local (VITE_API_URL=${CLOUDFRONT_API_URL})"

echo ""
echo "🏗️  Building frontend..."
(cd "$SCRIPT_DIR/.." && pnpm build)

echo ""
make -C "$SCRIPT_DIR" deploy-site
