#!/bin/bash
set -e

# 共有ファイルのクリーンアップ
rm -f $ENV_FILE 2>/dev/null || true

# 既存のイベントソースマッピングを削除
echo "Cleaning up existing event source mappings..."
event_source_mappings=$(aws lambda list-event-source-mappings --function-name $USAGE_EVENT_CONSUMER_NAME --endpoint-url $AWS_ENDPOINT_URL --output text --query 'EventSourceMappings[].UUID' 2>/dev/null)
if [ ! -z "$event_source_mappings" ]; then
    for uuid in $event_source_mappings; do
        aws lambda delete-event-source-mapping --uuid $uuid --endpoint-url $AWS_ENDPOINT_URL > /dev/null 2>&1
    done
fi

# 既存のLambda関数を削除（存在する場合）
echo "Cleaning up existing Lambda functions..."
lambda_functions=$(aws lambda list-functions --endpoint-url $AWS_ENDPOINT_URL --output text --query 'Functions[].FunctionName' 2>/dev/null)
if [ ! -z "$lambda_functions" ]; then
    for function_name in $lambda_functions; do
        echo "Deleting Lambda function: $function_name"
        aws lambda delete-function --function-name $function_name --endpoint-url $AWS_ENDPOINT_URL > /dev/null 2>&1
    done
fi

# 既存のキューを削除
echo "Cleaning up existing queues..."
queue_urls=$(aws sqs list-queues --endpoint-url $AWS_ENDPOINT_URL --output text --query 'QueueUrls[]' 2>/dev/null)
if [ -n "$queue_urls" ] && [ "$queue_urls" != "None" ]; then
    for queue_url in $queue_urls; do
        echo "Deleting SQS queue: $queue_url"
        aws sqs delete-queue --queue-url $queue_url --endpoint-url $AWS_ENDPOINT_URL > /dev/null 2>&1
    done
fi



# 既存のIAMロールを削除
echo "Cleaning up existing IAM roles..."
roles=$(aws iam list-roles --endpoint-url $AWS_ENDPOINT_URL --output text --query 'Roles[].RoleName' 2>/dev/null)
if [ ! -z "$roles" ]; then
    for role_name in $roles; do
        echo "Deleting IAM role: $role_name"
        # ロールに関連付けられたポリシーを削除
        policies=$(aws iam list-role-policies --role-name $role_name --endpoint-url $AWS_ENDPOINT_URL --output text --query 'PolicyNames[]' 2>/dev/null)
        if [ ! -z "$policies" ]; then
            for policy_name in $policies; do
                aws iam delete-role-policy --role-name $role_name --policy-name $policy_name --endpoint-url $AWS_ENDPOINT_URL > /dev/null 2>&1
            done
        fi
        # ロールを削除
        aws iam delete-role --role-name $role_name --endpoint-url $AWS_ENDPOINT_URL > /dev/null 2>&1
    done
fi


# 既存のS3バケットを削除
echo "Cleaning up existing S3 buckets..."
buckets=$(aws s3api list-buckets --endpoint-url $AWS_ENDPOINT_URL --output text --query 'Buckets[].Name' 2>/dev/null)
if [ ! -z "$buckets" ]; then
    for bucket_name in $buckets; do
        echo "Deleting S3 bucket: $bucket_name"
        # バケット内のオブジェクトを削除
        object_keys=$(aws s3api list-objects --bucket $bucket_name --endpoint-url $AWS_ENDPOINT_URL --output text --query 'Contents[].Key' 2>/dev/null)
        if [ ! -z "$object_keys" ]; then
            for object_key in $object_keys; do
                aws s3api delete-object --bucket $bucket_name --key "$object_key" --endpoint-url $AWS_ENDPOINT_URL > /dev/null 2>&1
            done
        fi
        # バケットを削除
        aws s3api delete-bucket --bucket $bucket_name --endpoint-url $AWS_ENDPOINT_URL > /dev/null 2>&1
    done
fi


# 既存のUserPoolを削除
echo "Cleaning up existing User Pools..."
user_pools=$(aws cognito-idp list-user-pools --max-results 60 --endpoint-url $AWS_ENDPOINT_URL --output text --query 'UserPools[].Id' 2>/dev/null)
if [ -n "$user_pools" ] && [ "$user_pools" != "None" ]; then
    for pool_id in $user_pools; do
        echo "Deleting UserPool: $pool_id"
        aws cognito-idp delete-user-pool --user-pool-id $pool_id --endpoint-url $AWS_ENDPOINT_URL > /dev/null 2>&1
    done
fi


echo "✅ Cleanup completed!"
