#!/bin/bash
set -e

echo "Setting up Usage Event Pipeline..."

LAMBDA_DUMMY_ROLE_ARN="arn:aws:iam::000000000000:role/dummy"
LAMBDA_SOURCE_DIR="/backend/"
LAMBDA_BUILD_DIR="/tmp/lambda/"
LAMBDA_ZIP_PATH="$LAMBDA_BUILD_DIR/usage_event_consumer.zip"


echo "🚀 Setting up Usage Event S3 Bucket..."

aws s3api create-bucket --bucket $USAGE_EVENT_STORAGE_NAME \
  --region $AWS_DEFAULT_REGION \
  --create-bucket-configuration LocationConstraint=$AWS_DEFAULT_REGION \
  --endpoint-url $AWS_ENDPOINT_URL

aws iam create-role --role-name $S3_ROLE_NAME \
  --assume-role-policy-document "{
    \"Version\": \"2012-10-17\",
    \"Statement\": [
        {
            \"Effect\": \"Allow\",
            \"Principal\": {
                \"AWS\": \"${LAMBDA_DUMMY_ROLE_ARN}\"
            },
            \"Action\": [
                \"sts:AssumeRole\",
                \"sts:TagSession\"
            ]
        }
    ]
}" \
  --endpoint-url $AWS_ENDPOINT_URL

aws iam put-role-policy \
  --role-name $S3_ROLE_NAME \
  --policy-name S3AccessPolicy \
  --policy-document \
"{
    \"Version\": \"2012-10-17\",
    \"Statement\": [
        {
            \"Condition\": {
                \"StringLike\": {
                    \"s3:prefix\": [
                        \"\${aws:PrincipalTag/tenant_id}/*\"
                    ]
                }
            },
            \"Action\": \"s3:ListBucket\",
            \"Resource\": \"arn:aws:s3:::${USAGE_EVENT_STORAGE_NAME}\",
            \"Effect\": \"Allow\"
        },
        {
            \"Action\": [
                \"s3:DeleteObject\",
                \"s3:GetObject\",
                \"s3:PutObject\"
            ],
            \"Resource\": \"arn:aws:s3:::${USAGE_EVENT_STORAGE_NAME}/${aws:PrincipalTag/tenant_id}/*\",
            \"Effect\": \"Allow\"
        }
    ]
}" \
  --endpoint-url $AWS_ENDPOINT_URL


echo "🚀 Setting up Usage Event Consumer SQS..."

aws sqs create-queue --queue-name $USAGE_EVENT_DLQ_NAME \
  --endpoint-url $AWS_ENDPOINT_URL
USAGE_EVENT_DLQ_ARN="arn:aws:sqs:$AWS_DEFAULT_REGION:000000000000:$USAGE_EVENT_DLQ_NAME"

aws sqs create-queue --queue-name $USAGE_EVENT_QUEUE_NAME \
  --attributes '{
    "RedrivePolicy": "{\"deadLetterTargetArn\":\"'$USAGE_EVENT_DLQ_ARN'\",\"maxReceiveCount\":3}"
  }' \
  --endpoint-url $AWS_ENDPOINT_URL


echo "Waiting for Lambda function '$USAGE_EVENT_CONSUMER_NAME' to be ready..."

# deploy.sh が実行されて関数が作成されるまで待機する (タイムアウトは60秒)
timeout 60s bash -c \
  "until aws lambda get-function --function-name $USAGE_EVENT_CONSUMER_NAME > /dev/null 2>&1; do \
    echo -n '.'; \
    sleep 2; \
  done"

echo "Function found. Creating event source mapping..."

echo "🚀 Setting up Usage Event Consumer Event Source Mapping..."
aws lambda create-event-source-mapping --function-name $USAGE_EVENT_CONSUMER_NAME \
  --event-source-arn arn:aws:sqs:$AWS_DEFAULT_REGION:000000000000:$USAGE_EVENT_QUEUE_NAME \
  --endpoint-url $AWS_ENDPOINT_URL


echo "✅ Setting up Usage Event Pipeline completed!"

if [ "$DEBUG_LAMBDA" = "1" ]; then
  echo "Tailing Lambda logs for debugging..."
  aws logs tail /aws/lambda/$USAGE_EVENT_CONSUMER_NAME --follow
fi
