#!/usr/bin/env bash
# check-gitlab-project.sh — verify GitLab project setup for the release pipeline.
#
# Usage: GITLAB_PAT=<pat> ./scripts/ci/check-gitlab-project.sh
#
# Prints:
#   - Numeric project ID (store as GITLAB_PROJECT_ID secret)
#   - Whether "Prevent approval by author" is OFF (required for self-approve)
set -euo pipefail

: "${GITLAB_PAT:?GITLAB_PAT required}"
GITLAB_HOST="${GITLAB_HOST:-https://teamscore.gitlab.yandexcloud.net}"
GITLAB_PROJECT_PATH="${GITLAB_PROJECT_PATH:-aeroflot2/flights-front}"

command -v jq >/dev/null 2>&1 || { echo "fatal: jq required" >&2; exit 2; }

ENCODED_PATH=$(printf '%s' "$GITLAB_PROJECT_PATH" | sed 's|/|%2F|g')
PROJECT_URL="${GITLAB_HOST}/api/v4/projects/${ENCODED_PATH}"

echo "Querying $PROJECT_URL"
resp=$(curl -fsS -H "PRIVATE-TOKEN: ${GITLAB_PAT}" "$PROJECT_URL") || {
  echo "fatal: project lookup failed (check PAT scopes: api + write_repository)" >&2
  exit 1
}

PROJECT_ID=$(printf '%s' "$resp" | jq -r '.id')
NAMESPACE=$(printf '%s' "$resp" | jq -r '.namespace.full_path')
DEFAULT_BRANCH=$(printf '%s' "$resp" | jq -r '.default_branch')

echo
echo "✅ Project: ${NAMESPACE}/$(printf '%s' "$resp" | jq -r '.path')"
echo "   ID:               ${PROJECT_ID}    ← store as Gitea secret GITLAB_PROJECT_ID"
echo "   Default branch:   ${DEFAULT_BRANCH}"

# Check approval settings
APPROVALS_URL="${GITLAB_HOST}/api/v4/projects/${PROJECT_ID}/approvals"
appr=$(curl -fsS -H "PRIVATE-TOKEN: ${GITLAB_PAT}" "$APPROVALS_URL" 2>/dev/null) || appr='{}'
DISABLE_OVERRIDING=$(printf '%s' "$appr" | jq -r '.disable_overriding_approvers_per_merge_request // false')
PREVENT_AUTHOR=$(printf '%s' "$appr" | jq -r '.merge_requests_author_approval // null')

echo
echo "Approval settings:"
echo "   merge_requests_author_approval: ${PREVENT_AUTHOR}"
echo "   disable_overriding_approvers:   ${DISABLE_OVERRIDING}"

# In GitLab API, merge_requests_author_approval=true means *allow* author approval.
case "$PREVENT_AUTHOR" in
  true)  echo "   ✅ Self-approve allowed." ;;
  false) echo "   ❌ Self-approve BLOCKED. Uncheck 'Prevent approval by author' in project settings." ;;
  *)     echo "   ⚠️  Could not read approval setting; verify in GitLab UI." ;;
esac

# Check whether the runner can authenticate to push (try a HEAD on /info/refs).
echo
echo "Verifying push auth via HTTPS..."
PUSH_URL="${GITLAB_HOST}/${GITLAB_PROJECT_PATH}.git/info/refs?service=git-receive-pack"
http_code=$(curl -s -o /dev/null -w "%{http_code}" -u "oauth2:${GITLAB_PAT}" "$PUSH_URL" || echo "000")
case "$http_code" in
  200) echo "   ✅ Push auth ok (HTTP 200)" ;;
  *)   echo "   ⚠️  Push auth returned HTTP $http_code — verify PAT scope includes write_repository" ;;
esac
