#!/bin/bash
create_issue() {
    local title="$1"
    local project_key="$2"
    local issue_type="$3"
    local parent_issue_key="$4"
    
    AUTH=$(echo -ne "$JIRA_USERNAME:$JIRA_API_KEY" | base64 --wrap 0)
    
    local parent_issue=$(curl -s -H "Authorization: Basic $AUTH" \
    "$JIRA_SERVER/rest/api/3/issue/$parent_issue_key")
    
    local parent_fix_versions=$(echo $parent_issue | jq -r '.fields.fixVersions')
    
    local created_issue=$(curl -X POST -H "Content-Type: application/json" \
        -H "Authorization: Basic $AUTH" \
        -d '{
      "fields": {
        "summary": "'"$title"'",
        "project": {
          "key": "'"$project_key"'"
        },
        "issuetype": {
          "name": "'"$issue_type"'"
        },
        "parent": {
          "key": "'"$parent_issue_key"'"
        },
        "fixVersions": '"$parent_fix_versions"'
      }
        }' \
    "$JIRA_SERVER/rest/api/3/issue")
    
    local created_issue_id=$(echo $created_issue | jq -r '.id')
    
    curl -X PUT -H "Content-Type: application/json" \
    -H "Authorization: Basic $AUTH" \
    -d '{
      "fields": {
        "fixVersions": '"$parent_fix_versions"'
      }
    }' \
    "$JIRA_SERVER/rest/api/3/issue/$created_issue_id"
}

extract_uuid() {
    local url="$1"
    local uuid_regex='[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}'
    if [[ "$url" =~ $uuid_regex ]]; then
        echo "${BASH_REMATCH}"
    else
        echo "No UUID found in the URL."
    fi
}

update_issue_status() {
    local issue_key="$1"
    local status_name="$2"
    
    AUTH=$(echo -ne "$JIRA_USERNAME:$JIRA_API_KEY" | base64 --wrap 0)
    
    local transitions=$(curl -s -H "Authorization: Basic $AUTH" \
    "$JIRA_SERVER/rest/api/3/issue/$issue_key/transitions")
    
    local transition_id=$(echo "$transitions" | jq -r --arg status_name "$status_name" '
  .transitions[] | select(.isAvailable == true and .to.name == $status_name) | .id
    ')
    
    if [ -z "$transition_id" ]; then
        echo "BadRequestError"
        exit 1
    else
        curl -X POST -H "Content-Type: application/json" \
        -H "Authorization: Basic $AUTH" \
        -d '{
        "transition": {
          "id": "'"$transition_id"'"
        }
        }' \
        "$JIRA_SERVER/rest/api/3/issue/$issue_key/transitions"
    fi
}

add_attachments() {
    AUTH=$(echo -ne "$JIRA_USERNAME:$JIRA_API_KEY" | base64 --wrap 0)
    
    local issue_key="$1"
    shift
    local attachments=("$@")
    
    echo $issue_key
    echo $attachments
    
    local form_data=""
    for attachment in "${attachments[@]}"; do
        form_data+="--form file=@$attachment "
    done
    
    echo $form_data
    
    echo $(curl -X POST $form_data \
        -H "X-Atlassian-Token: no-check" \
        -H "Authorization: Basic $AUTH" \
    "$JIRA_SERVER/rest/api/3/issue/$issue_key/attachments")
}

add_comment() {
    set -x  # Enable script tracing
    AUTH=$(echo -ne "$JIRA_USERNAME:$JIRA_API_KEY" | base64 --wrap 0)
    local issue_key="$1"
    shift
    local comment_items_input=("$@")
    local comment_json="[]"
    
    for item in "${comment_items_input[@]}"; do
        if [ -e "$item" ]; then
            # If it's a file path
            local attachment=$(add_attachments "$issue_key" "$item")
            local id=$(echo $attachment | grep -oP '"id":\s*"\K[^"]+')
            
            local attachment_content=$(curl -s -I -L -H "Authorization: Basic $AUTH" "$JIRA_SERVER/rest/api/3/attachment/content/$id" \
            | grep -i "Location:" | tail -1 | awk '{print $2}' | tr -d '\r')
            echo "$JIRA_SERVER/rest/api/3/attachment/content/$id"
            echo "$attachment_content"
            
            local uuid=$(extract_uuid "$attachment_content")
            echo "$uuid"
            
            json_object=$(jq -n --arg uuid "$uuid" '{ type: "mediaSingle", attrs: { layout: "align-start" }, content: [{ type: "media", attrs: { type: "file", id: $uuid, width: 200, height: 200, collection: "", alt: "" } }]}')
            
            comment_json=$(echo "$comment_json" | jq --argjson obj "$json_object" '. += [$obj]')
        else
            # If it's a string
            json_object=$(jq -n --arg text "$item" '{ type: "paragraph", content: [{ type: "text", text: $text }]}')
            
            comment_json=$(echo "$comment_json" | jq --argjson obj "$json_object" '. += [$obj]')
        fi
    done
    
    request=$(jq -n --argjson content "$comment_json" '{body: { type: "doc", version: 1, content: $content }}')
    
    curl -X POST -H "Content-Type: application/json" \
    -H "Authorization: Basic $AUTH" \
    -d "$request" \
    "$JIRA_SERVER/rest/api/3/issue/$issue_key/comment"
}

if [[ $# -gt 0 ]]; then # IF function call passed in
  "$@"  # Call function
fi