#!/bin/bash
# Test script to find the correct Gitea package link API endpoint
# Usage: Set GITEA_TOKEN environment variable and run this script

if [ -z "$GITEA_TOKEN" ]; then
  echo "Error: GITEA_TOKEN environment variable not set"
  echo "Usage: GITEA_TOKEN=your_token ./test-link-api.sh"
  exit 1
fi

PACKAGE="stack-api"
OWNER="mosaic"
REPO="stack"
BASE_URL="https://git.mosaicstack.dev"

echo "Testing different API endpoint formats for package linking..."
echo "Package: $PACKAGE"
echo "Owner: $OWNER"
echo "Repo: $REPO"
echo ""

# Test 1: Current format with /-/
echo "Test 1: POST /api/v1/packages/$OWNER/container/$PACKAGE/-/link/$REPO"
STATUS=$(curl -s -o /dev/null -w "%{http_code}" -X POST \
  -H "Authorization: token $GITEA_TOKEN" \
  "$BASE_URL/api/v1/packages/$OWNER/container/$PACKAGE/-/link/$REPO")
echo "Status: $STATUS"
echo ""

# Test 2: Without /-/
echo "Test 2: POST /api/v1/packages/$OWNER/container/$PACKAGE/link/$REPO"
STATUS=$(curl -s -o /dev/null -w "%{http_code}" -X POST \
  -H "Authorization: token $GITEA_TOKEN" \
  "$BASE_URL/api/v1/packages/$OWNER/container/$PACKAGE/link/$REPO")
echo "Status: $STATUS"
echo ""

# Test 3: With PUT instead of POST (old method)
echo "Test 3: PUT /api/v1/packages/$OWNER/container/$PACKAGE/-/link/$REPO"
STATUS=$(curl -s -o /dev/null -w "%{http_code}" -X PUT \
  -H "Authorization: token $GITEA_TOKEN" \
  "$BASE_URL/api/v1/packages/$OWNER/container/$PACKAGE/-/link/$REPO")
echo "Status: $STATUS"
echo ""

# Test 4: Different path structure
echo "Test 4: PUT /api/v1/packages/$OWNER/$PACKAGE/link/$REPO"
STATUS=$(curl -s -o /dev/null -w "%{http_code}" -X PUT \
  -H "Authorization: token $GITEA_TOKEN" \
  "$BASE_URL/api/v1/packages/$OWNER/$PACKAGE/link/$REPO")
echo "Status: $STATUS"
echo ""

# Test 5: Check if package exists at all
echo "Test 5: GET /api/v1/packages/$OWNER/container/$PACKAGE"
STATUS=$(curl -s -w "%{http_code}" -X GET \
  -H "Authorization: token $GITEA_TOKEN" \
  "$BASE_URL/api/v1/packages/$OWNER/container/$PACKAGE" | tail -1)
echo "Status: $STATUS"
echo ""

# Test 6: List all packages for owner
echo "Test 6: GET /api/v1/packages/$OWNER"
echo "First 3 packages:"
curl -s -X GET \
  -H "Authorization: token $GITEA_TOKEN" \
  "$BASE_URL/api/v1/packages/$OWNER?type=container&page=1&limit=10" | head -30
echo ""

echo "=== Instructions ==="
echo "1. Run this script with: GITEA_TOKEN=your_token ./test-link-api.sh"
echo "2. Look for Status: 200, 201, 204 (success) or 400 (already linked)"
echo "3. Status 404 means the endpoint doesn't exist"
echo "4. Status 401/403 means authentication issue"
