#!/bin/bash

# Week 3: Create Jira Dashboards
# Creates project-specific dashboards for PROD, MARK, SUPP, OPS

ATLASSIAN_SITE_URL="https://ai-impress.atlassian.net"
ATLASSIAN_EMAIL="v.samoilenko@ai-impress.com"
ATLASSIAN_API_TOKEN="ATATT3xFfGF0ABlJi4MORJ1Mlyb6ZhR-I984TYCrUhoGH3yHf0bjhZKkJ_pk27s6mrb-GVoVtr0bXmXWtYDyQt0QL0Ut6BNpmfrz1ATJnIbqAsWVuWeKHxqyKJ8gZVApsi8OBc-jC2BVoG9TUEBDPDMWmG_0JG3zFU6bv8jTmGecwe2xlZzTiJo=E0093140"
JIRA_AUTH=$(echo -n "${ATLASSIAN_EMAIL}:${ATLASSIAN_API_TOKEN}" | base64)

echo "=== Week 3: Creating Jira Dashboards ==="
echo ""

# Function to create dashboard
create_dashboard() {
    local name=$1
    local description=$2
    local project=$3

    echo "Creating dashboard: $name..."

    # Create dashboard using Jira API v3
    # Note: Cannot share with public in this Jira instance, so only use edit permissions
    local json_data="{
        \"name\": \"$name\",
        \"description\": \"$description\",
        \"editPermissions\": [],
        \"sharePermissions\": []
    }"

    curl -s -X POST \
      "${ATLASSIAN_SITE_URL}/rest/api/3/dashboard" \
      -H "Authorization: Basic ${JIRA_AUTH}" \
      -H "Content-Type: application/json" \
      -d "$json_data" > /tmp/dashboard_response.json

    if grep -q "\"id\":" /tmp/dashboard_response.json; then
        DASHBOARD_ID=$(grep -o '"id":"[^"]*"' /tmp/dashboard_response.json | head -1 | cut -d'"' -f4)
        echo "✓ Dashboard created (ID: $DASHBOARD_ID)"
    else
        ERROR=$(grep -o '"message":"[^"]*"' /tmp/dashboard_response.json | head -1 | cut -d'"' -f4)
        if [ -z "$ERROR" ]; then
            ERROR=$(cat /tmp/dashboard_response.json | head -c 200)
        fi
        echo "❌ Error: $ERROR"
    fi
    echo ""
}

# PROD Dashboard
echo "--- PROD Project Dashboard ---"
create_dashboard \
    "PROD - Development Overview" \
    "Dashboard showing current sprint status, recent deployments, and bug tracking for PROD project" \
    "PROD"

# MARK Dashboard
echo "--- MARK Project Dashboard ---"
create_dashboard \
    "MARK - Sales Pipeline" \
    "Dashboard showing leads pipeline, conversion metrics, and opportunity tracking for MARK project" \
    "MARK"

# SUPP Dashboard
echo "--- SUPP Project Dashboard ---"
create_dashboard \
    "SUPP - Support Metrics" \
    "Dashboard showing ticket queue, response times, and customer satisfaction metrics for SUPP project" \
    "SUPP"

# OPS Dashboard
echo "--- OPS Project Dashboard ---"
create_dashboard \
    "OPS - Operations Status" \
    "Dashboard showing operational tasks, approvals, and invoice tracking for OPS project" \
    "OPS"

# Executive Dashboard
echo "--- Executive Dashboard ---"
create_dashboard \
    "Executive - All Critical Issues" \
    "Cross-project dashboard showing all critical and blocker issues across PROD, MARK, SUPP, OPS" \
    "EXEC"

echo "✓ Dashboards creation complete (5 total)"
echo ""
echo "Next: Add gadgets to dashboards and configure automation rules"
