#
# Copyright Super iPaaS Integration LLC, an IBM Company 2024
#
stage=$1
echo "Checking approval"
source "${ONE_PIPELINE_PATH}"/tools/get_repo_params

APP_TOKEN_PATH="./app-token"
PR_URL=$(get_env PR_URL "")
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")
curl -L -H "Authorization: Bearer $(cat ${APP_TOKEN_PATH})" -H "Accept: application/vnd.github+json" "${APP_API_URL}/repos/${APP_REPO_OWNER}/${APP_REPO_NAME}/branches/$branch/protection" > "$branch_protection_content"
if [ "$stage" = "merge" ]; then
    TIME_OUT=1
else           
   TIME_OUT=1
fi
approval_count
start_time=$(date +%s)
APPROVAL_THRESHOLD=$(get_env approval_count)
PAGE_SIZE=100
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."
    fi
    # Check if 1 hour has passed
    current_time=$(date +%s)
    elapsed_time=$((current_time - start_time))
    if [ "$elapsed_time" -ge "$TIME_OUT" ]; then
        echo "Failure: Timeout after 1 hour. PR doesn't have the required approvals."
        if [ "$stage" = "merge" ]; then
           exit 1
        fi
    fi
    echo "Not enough approvals. Checking again in 30 seconds..."
    sleep 30
done
