#!/usr/bin/env bash
# Crée une issue Gitea via l'API.
# Usage: GITEA_TOKEN=xxx ./scripts/create-gitea-issue.sh
# Ou: mettre le token dans .gitea-token à la racine du projet.

set -e
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

TITLE="$1"
BODY="$2"
if [ -z "$TITLE" ]; then
  echo "Usage: $0 \"Titre de l'issue\" \"Corps (optionnel)\""
  exit 1
fi

# Build JSON (escape body for JSON)
BODY_ESC=$(echo "$BODY" | jq -Rs . 2>/dev/null || echo "null")
if [ "$BODY_ESC" = "null" ] || [ -z "$BODY" ]; then
  PAYLOAD=$(jq -n --arg t "$TITLE" '{title: $t}')
else
  PAYLOAD=$(jq -n --arg t "$TITLE" --arg b "$BODY" '{title: $t, body: $b}')
fi

RESP=$(curl -s -w "\n%{http_code}" -X POST \
  -H "Authorization: token $GITEA_TOKEN" \
  -H "Content-Type: application/json" \
  -d "$PAYLOAD" \
  "$BASE_URL/repos/$REPO/issues")
HTTP_CODE=$(echo "$RESP" | tail -1)
BODY_RESP=$(echo "$RESP" | sed '$d')

if [ "$HTTP_CODE" = "201" ]; then
  ISSUE_NUM=$(echo "$BODY_RESP" | jq -r .number)
  echo "Issue #$ISSUE_NUM créée."
  echo "$BODY_RESP" | jq .
else
  echo "Erreur HTTP $HTTP_CODE: $BODY_RESP"
  exit 1
fi
