#!/usr/bin/env bash
# Ferme une issue Gitea via l'API.
# Usage: GITEA_TOKEN=votre_token ./scripts/gitea-close-issue.sh [numéro]
# Exemple: GITEA_TOKEN=xxx ./scripts/gitea-close-issue.sh 83

set -e
ISSUE="${1:-83}"
BASE_URL="${GITEA_URL:-https://git.ptits-pas.fr/api/v1}"
REPO="jmartin/petitspas"

if [ -z "$GITEA_TOKEN" ]; then
  if [ -f .gitea-token ]; then
    GITEA_TOKEN=$(cat .gitea-token)
  fi
fi

if [ -z "$GITEA_TOKEN" ]; then
  echo "Définir GITEA_TOKEN ou créer .gitea-token avec votre token Gitea."
  exit 1
fi

echo "Fermeture de l'issue #$ISSUE..."
RESP=$(curl -s -w "\n%{http_code}" -X PATCH \
  -H "Authorization: token $GITEA_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"state":"closed"}' \
  "$BASE_URL/repos/$REPO/issues/$ISSUE")
HTTP_CODE=$(echo "$RESP" | tail -1)
BODY=$(echo "$RESP" | sed '$d')

if [ "$HTTP_CODE" = "200" ] || [ "$HTTP_CODE" = "201" ]; then
  echo "Issue #$ISSUE fermée."
else
  echo "Erreur HTTP $HTTP_CODE: $BODY"
  exit 1
fi
