#
# Copyright Super iPaaS Integration LLC, an IBM Company 2024
#

echo "Checking approval"
source "${ONE_PIPELINE_PATH}"/tools/get_repo_params
PR_URL=$(get_env PR_URL "")
APP_TOKEN_PATH="./app-token" 

start_time=$(date +%s)
APPROVAL_THRESHOLD=$(get_env approval_count)
PAGE_SIZE=100
read -r APP_REPO_NAME APP_REPO_OWNER APP_SCM_TYPE APP_API_URL < <(get_repo_params "$(load_repo app-repo url)" "$APP_TOKEN_PATH")
while true; do
    reviews="[]"
    page=1
    while true; do
        response=$(curl -s --fail --request GET \
            --url "${PR_URL}/reviews?page=$page" \
            --header "Authorization: Bearer $(cat "${APP_TOKEN_PATH}")")
        # Check if the curl command succeeded
        if [ $? -ne 0 ]; then
            echo "Error: Failed to fetch reviews from GitHub API."
            exit 1
        fi
        current_page_reviews=$(echo "$response" | jq '.')
        # Append current page reviews to the reviews array
        reviews=$(echo "$reviews" | jq --argjson newReviews "$current_page_reviews" '. + $newReviews')
        # Break if fewer than PAGE_SIZE reviews on this page
        if [ $(echo "$current_page_reviews" | jq 'length') -lt $PAGE_SIZE ]; then
            break
        fi
        # Increment the page number
        page=$((page + 1))
    done
    # Filter and count unique approved reviews
    approved_reviews=$(echo "$reviews" | jq '[ .[] | select(.state == "APPROVED") | .user.login ] | unique | length')
    echo "Current approved reviews: $approved_reviews"
    if [ "$approved_reviews" -ge $APPROVAL_THRESHOLD ]; then
        echo "Success: PR has at least $APPROVAL_THRESHOLD approvals from different users."
        break
    else
        echo "Failure: PR doesn't meet the approval threshold."
        exit 1
    fi
done
