#!/bin/bash
# Add a Jira issue to the active sprint of its project's board

set -e

# Arguments
ISSUE_KEY="$1"
PROJECT_KEY="${2:-$JIRA_PROJECT_PREFIX}"

# Validation
if [ -z "$ISSUE_KEY" ]; then
    echo "Error: Missing issue key" >&2
    echo "Usage: $0 <issue-key> [project-key]" >&2
    exit 1
fi

if [ -z "$PROJECT_KEY" ]; then
    echo "Error: Missing project key (argument or JIRA_PROJECT_PREFIX)" >&2
    exit 1
fi

# Check environment variables
if [ -z "$ATLASSIAN_SITE_NAME" ] || [ -z "$ATLASSIAN_USER_EMAIL" ] || [ -z "$ATLASSIAN_API_TOKEN" ]; then
    echo "Error: Jira environment variables not set" >&2
    echo "Required: ATLASSIAN_SITE_NAME, ATLASSIAN_USER_EMAIL, ATLASSIAN_API_TOKEN" >&2
    exit 1
fi

# Find the project's board
BOARD_ID=$(curl -s -X GET \
    -H "Content-Type: application/json" \
    -u "${ATLASSIAN_USER_EMAIL}:${ATLASSIAN_API_TOKEN}" \
    "${ATLASSIAN_SITE_NAME}/rest/agile/1.0/board?projectKeyOrId=${PROJECT_KEY}" \
    | jq -r '.values[0].id // empty')

if [ -z "$BOARD_ID" ]; then
    echo "Error: No board found for project ${PROJECT_KEY}" >&2
    exit 1
fi

# Find the active sprint on that board
SPRINT_JSON=$(curl -s -X GET \
    -H "Content-Type: application/json" \
    -u "${ATLASSIAN_USER_EMAIL}:${ATLASSIAN_API_TOKEN}" \
    "${ATLASSIAN_SITE_NAME}/rest/agile/1.0/board/${BOARD_ID}/sprint?state=active" \
    | jq '.values[0] // empty')

if [ -z "$SPRINT_JSON" ]; then
    echo "Error: No active sprint found on board ${BOARD_ID}" >&2
    exit 1
fi

SPRINT_ID=$(echo "$SPRINT_JSON" | jq -r '.id')
SPRINT_NAME=$(echo "$SPRINT_JSON" | jq -r '.name')

# Add the issue to the active sprint
HTTP_STATUS=$(curl -s -o /dev/null -w "%{http_code}" -X POST \
    -H "Content-Type: application/json" \
    -u "${ATLASSIAN_USER_EMAIL}:${ATLASSIAN_API_TOKEN}" \
    -d "$(jq -n --arg key "$ISSUE_KEY" '{issues: [$key]}')" \
    "${ATLASSIAN_SITE_NAME}/rest/agile/1.0/sprint/${SPRINT_ID}/issue")

if [ "$HTTP_STATUS" != "204" ]; then
    echo "Error: Failed to add ${ISSUE_KEY} to sprint ${SPRINT_ID} (HTTP ${HTTP_STATUS})" >&2
    exit 1
fi

jq -n --arg issue "$ISSUE_KEY" --argjson sprint_id "$SPRINT_ID" --arg sprint_name "$SPRINT_NAME" \
    '{success: true, issue: $issue, sprint_id: $sprint_id, sprint_name: $sprint_name}'
