#!/bin/bash
# Create a link between two Jira issues (default link type: Relates)

set -e

# Arguments
INWARD_KEY=""
OUTWARD_KEY=""
LINK_TYPE="Relates"

while [ $# -gt 0 ]; do
    case "$1" in
        --type)
            if [ -z "$2" ]; then
                echo "Error: --type requires a value" >&2
                exit 1
            fi
            LINK_TYPE="$2"
            shift 2
            ;;
        *)
            if [ -z "$INWARD_KEY" ]; then
                INWARD_KEY="$1"
            elif [ -z "$OUTWARD_KEY" ]; then
                OUTWARD_KEY="$1"
            else
                echo "Error: Unexpected argument: $1" >&2
                exit 1
            fi
            shift
            ;;
    esac
done

# Validation
if [ -z "$INWARD_KEY" ] || [ -z "$OUTWARD_KEY" ]; then
    echo "Error: Missing required arguments" >&2
    echo "Usage: $0 <inward-issue-key> <outward-issue-key> [--type <link-type>]" >&2
    echo "" >&2
    echo "Examples:" >&2
    echo "  Relates (default): $0 QUE-327 QUE-321" >&2
    echo "  Explicit type: $0 QUE-327 QUE-321 --type 'Relates'" >&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
    exit 1
fi

# Build JSON payload
PAYLOAD=$(jq -n \
    --arg type "$LINK_TYPE" \
    --arg inward "$INWARD_KEY" \
    --arg outward "$OUTWARD_KEY" \
    '{
        type: { name: $type },
        inwardIssue: { key: $inward },
        outwardIssue: { key: $outward }
    }')

# Create link. Success is HTTP 201 with no body.
RESPONSE=$(curl -s -w '\n%{http_code}' -X POST \
    -H "Content-Type: application/json" \
    -u "${ATLASSIAN_USER_EMAIL}:${ATLASSIAN_API_TOKEN}" \
    -d "$PAYLOAD" \
    "${ATLASSIAN_SITE_NAME}/rest/api/2/issueLink")

STATUS=$(echo "$RESPONSE" | tail -n 1)
BODY=$(echo "$RESPONSE" | sed '$d')

if [ "$STATUS" != "201" ]; then
    echo "Error: link creation failed with HTTP ${STATUS}" >&2
    if [ -n "$BODY" ]; then
        echo "$BODY" | jq '.' >&2 2>/dev/null || echo "$BODY" >&2
    fi
    exit 1
fi

jq -n --arg inward "$INWARD_KEY" --arg outward "$OUTWARD_KEY" --arg type "$LINK_TYPE" \
    '{success: true, inward_issue: $inward, outward_issue: $outward, link_type: $type}'
