#!/bin/bash

# Atlassian API Utility Functions

# Source credentials
if [ -f "/opt/00-infrastructure/atlassian/.env.atlassian" ]; then
    source /opt/00-infrastructure/atlassian/.env.atlassian
elif [ -f "/tmp/atlassian-setup/credentials.env" ]; then
    source /tmp/atlassian-setup/credentials.env
fi

# API Helper Functions
api_call() {
    local method=$1
    local endpoint=$2
    local data=${3:-""}
    local output_file=${4:-"/tmp/api_response.json"}
    
    if [ "$method" = "POST" ] || [ "$method" = "PUT" ]; then
        curl -s -X "$method" \
            "${ATLASSIAN_SITE_URL}${endpoint}" \
            -H "Authorization: Basic ${JIRA_AUTH}" \
            -H "Content-Type: application/json" \
            -d "$data" > "$output_file"
    else
        curl -s -X "$method" \
            "${ATLASSIAN_SITE_URL}${endpoint}" \
            -H "Authorization: Basic ${JIRA_AUTH}" \
            -H "Content-Type: application/json" > "$output_file"
    fi
    
    cat "$output_file"
}

# Get project info
get_project() {
    local project_key=$1
    api_call "GET" "/rest/api/3/project/$project_key"
}

# List all projects
list_projects() {
    api_call "GET" "/rest/api/3/project/search?maxResults=50"
}

# Get custom fields
list_custom_fields() {
    api_call "GET" "/rest/api/3/customfield"
}

# Get project components
list_components() {
    local project_key=$1
    api_call "GET" "/rest/api/3/component?project=$project_key"
}

# Get filters
list_filters() {
    api_call "GET" "/rest/api/3/filter/search?maxResults=50"
}

# Get dashboards
list_dashboards() {
    api_call "GET" "/rest/api/3/dashboard/search?maxResults=50"
}

# Get issue link types
list_issue_link_types() {
    api_call "GET" "/rest/api/3/issueLinkType"
}

# Check server info
check_server_info() {
    api_call "GET" "/rest/api/3/serverInfo"
}
