#!/bin/bash
set -e

BASE_URL="https://jira-fixer.startdata.com.br"

echo "=== JIRA AI Fixer - End-to-End Test ==="
echo ""

# 1. Health check
echo "1. Testing API health..."
HEALTH=$(curl -s "$BASE_URL/api/health")
echo "   ✓ API: $HEALTH"
echo ""

# 2. Register user
echo "2. Registering admin user..."
REGISTER_RESP=$(curl -s -X POST "$BASE_URL/api/auth/register" \
  -H "Content-Type: application/json" \
  -d '{"email":"admin@startdata.com.br","password":"JiraFixer2026!","name":"Admin User"}')

TOKEN=$(echo "$REGISTER_RESP" | jq -r '.access_token')

if [ "$TOKEN" = "null" ] || [ -z "$TOKEN" ]; then
  echo "   Registration failed or user exists, trying login..."
  LOGIN_RESP=$(curl -s -X POST "$BASE_URL/api/auth/login" \
    -H "Content-Type: application/json" \
    -d '{"email":"admin@startdata.com.br","password":"JiraFixer2026!"}')
  TOKEN=$(echo "$LOGIN_RESP" | jq -r '.access_token')
fi

echo "   ✓ Token: ${TOKEN:0:20}..."
echo ""

# 3. Create issue for SUPP-6
echo "3. Creating issue for SUPP-6..."
ISSUE_RESP=$(curl -s -X POST "$BASE_URL/api/issues" \
  -H "Authorization: Bearer $TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "title": "Card validation accepts invalid card numbers (less than 16 digits)",
    "description": "The VALIDATE.CBL module currently accepts credit card numbers with 10 or more digits instead of exactly 16 digits.\n\nFile: src/cobol/VALIDATE.CBL\nParagraph: 1000-VALIDATE-CARD\nLine: 29\nExpected: Card number must be exactly 16 digits\nActual: Card number is accepted if >= 10 digits\n\nRepository: https://gitea.startdata.com.br/startdata/cobol-sample-app\nBranch: main\nCommit: 4fae19b",
    "external_key": "SUPP-6",
    "priority": "high",
    "repository": "https://gitea.startdata.com.br/startdata/cobol-sample-app"
  }')

ISSUE_ID=$(echo "$ISSUE_RESP" | jq -r '.id')
echo "   ✓ Issue created: ID=$ISSUE_ID"
echo ""

# 4. Wait for AI analysis (background task)
echo "4. Waiting for AI analysis (30s)..."
sleep 30

# 5. Check issue status
echo "5. Checking issue status..."
ISSUE_STATUS=$(curl -s "$BASE_URL/api/issues/$ISSUE_ID" \
  -H "Authorization: Bearer $TOKEN")

STATUS=$(echo "$ISSUE_STATUS" | jq -r '.status')
CONFIDENCE=$(echo "$ISSUE_STATUS" | jq -r '.confidence')
PR_URL=$(echo "$ISSUE_STATUS" | jq -r '.pr_url')

echo "   Status: $STATUS"
echo "   Confidence: $CONFIDENCE%"
echo "   PR URL: $PR_URL"
echo ""

# 6. Verify results
if [ "$STATUS" = "analyzed" ] && [ "$CONFIDENCE" -ge 70 ]; then
  echo "✅ E2E TEST PASSED!"
  echo "   - Issue analyzed successfully"
  echo "   - High confidence fix ($CONFIDENCE%)"
  if [ "$PR_URL" != "null" ]; then
    echo "   - PR created: $PR_URL"
  fi
else
  echo "⚠️  E2E TEST INCOMPLETE"
  echo "   Status: $STATUS (expected: analyzed)"
  echo "   Confidence: $CONFIDENCE% (expected: >= 70%)"
  echo "   This may take longer - check logs for details"
fi

echo ""
echo "=== Test Complete ==="
