#!/bin/bash
# AImpress - Remaining Tasks Script
# 1. Get field IDs for created select fields
# 2. Add options to select fields
# 3. Delete duplicate issues from KAN

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

echo "============================================"
echo "STEP 1: Get Custom Field IDs"
echo "============================================"

# Get all custom fields and filter select fields
echo "Fetching custom field IDs..."
FIELDS=$(curl -s -X GET \
  "${JIRA_URL}/rest/api/3/field" \
  -H "Authorization: Basic ${JIRA_AUTH}" \
  -H "Content-Type: application/json")

echo ""
echo "Select fields created:"
echo "$FIELDS" | jq -r '.[] | select(.custom == true and .schema.type == "option") | "  \(.id): \(.name)"'

echo ""
echo "All custom fields:"
echo "$FIELDS" | jq -r '.[] | select(.custom == true) | "  \(.id): \(.name) (\(.schema.type // "unknown"))"'

# Extract field IDs
LEAD_SOURCE_ID=$(echo "$FIELDS" | jq -r '.[] | select(.name == "Lead Source") | .id')
LEAD_STATUS_ID=$(echo "$FIELDS" | jq -r '.[] | select(.name == "Lead Status") | .id')
SERVICE_PACKAGE_ID=$(echo "$FIELDS" | jq -r '.[] | select(.name == "Service Package") | .id')
INVOICE_STATUS_ID=$(echo "$FIELDS" | jq -r '.[] | select(.name == "Invoice Status") | .id')
CONTRACT_TYPE_ID=$(echo "$FIELDS" | jq -r '.[] | select(.name == "Contract Type") | .id')
TICKET_CATEGORY_ID=$(echo "$FIELDS" | jq -r '.[] | select(.name == "Ticket Category") | .id')
SLA_PRIORITY_ID=$(echo "$FIELDS" | jq -r '.[] | select(.name == "SLA Priority") | .id')
ENVIRONMENT_ID=$(echo "$FIELDS" | jq -r '.[] | select(.name == "Environment") | .id')

echo ""
echo "Extracted IDs:"
echo "  Lead Source: $LEAD_SOURCE_ID"
echo "  Lead Status: $LEAD_STATUS_ID"
echo "  Service Package: $SERVICE_PACKAGE_ID"
echo "  Invoice Status: $INVOICE_STATUS_ID"
echo "  Contract Type: $CONTRACT_TYPE_ID"
echo "  Ticket Category: $TICKET_CATEGORY_ID"
echo "  SLA Priority: $SLA_PRIORITY_ID"
echo "  Environment: $ENVIRONMENT_ID"

echo ""
echo "============================================"
echo "STEP 2: Add Options to Select Fields"
echo "============================================"

add_options() {
  local field_id="$1"
  local field_name="$2"
  local options_json="$3"

  if [ -z "$field_id" ] || [ "$field_id" == "null" ]; then
    echo "⚠️  Skipping $field_name - field not found"
    return
  fi

  echo ""
  echo "Processing: $field_name ($field_id)"

  # Get context ID
  CONTEXT=$(curl -s -X GET \
    "${JIRA_URL}/rest/api/3/field/${field_id}/context" \
    -H "Authorization: Basic ${JIRA_AUTH}" \
    -H "Content-Type: application/json")

  CONTEXT_ID=$(echo "$CONTEXT" | jq -r '.values[0].id')

  if [ -z "$CONTEXT_ID" ] || [ "$CONTEXT_ID" == "null" ]; then
    echo "  ⚠️  No context found for $field_name"
    return
  fi

  echo "  Context ID: $CONTEXT_ID"

  # Add options
  RESULT=$(curl -s -X POST \
    "${JIRA_URL}/rest/api/3/field/${field_id}/context/${CONTEXT_ID}/option" \
    -H "Authorization: Basic ${JIRA_AUTH}" \
    -H "Content-Type: application/json" \
    -d "$options_json")

  if echo "$RESULT" | jq -e '.options' > /dev/null 2>&1; then
    echo "  ✓ Options added successfully"
  else
    echo "  ⚠️  Response: $RESULT"
  fi
}

# Lead Source
add_options "$LEAD_SOURCE_ID" "Lead Source" '{
  "options": [
    {"value": "Website", "disabled": false},
    {"value": "Referral", "disabled": false},
    {"value": "LinkedIn", "disabled": false},
    {"value": "Webinar", "disabled": false},
    {"value": "Cold Outreach", "disabled": false},
    {"value": "Partner", "disabled": false},
    {"value": "Google Ads", "disabled": false},
    {"value": "Social Media", "disabled": false},
    {"value": "Other", "disabled": false}
  ]
}'

# Lead Status
add_options "$LEAD_STATUS_ID" "Lead Status" '{
  "options": [
    {"value": "New", "disabled": false},
    {"value": "Contacted", "disabled": false},
    {"value": "Qualified", "disabled": false},
    {"value": "Proposal Sent", "disabled": false},
    {"value": "Negotiation", "disabled": false},
    {"value": "Won", "disabled": false},
    {"value": "Lost", "disabled": false},
    {"value": "On Hold", "disabled": false}
  ]
}'

# Service Package
add_options "$SERVICE_PACKAGE_ID" "Service Package" '{
  "options": [
    {"value": "Starter (£450-850)", "disabled": false},
    {"value": "Growth (£950-1900)", "disabled": false},
    {"value": "Pro (£2400-6000)", "disabled": false},
    {"value": "Enterprise (£10K+)", "disabled": false},
    {"value": "Custom", "disabled": false}
  ]
}'

# Invoice Status
add_options "$INVOICE_STATUS_ID" "Invoice Status" '{
  "options": [
    {"value": "Draft", "disabled": false},
    {"value": "Sent", "disabled": false},
    {"value": "Viewed", "disabled": false},
    {"value": "Partial Payment", "disabled": false},
    {"value": "Paid", "disabled": false},
    {"value": "Overdue", "disabled": false},
    {"value": "Cancelled", "disabled": false}
  ]
}'

# Contract Type
add_options "$CONTRACT_TYPE_ID" "Contract Type" '{
  "options": [
    {"value": "Service Agreement", "disabled": false},
    {"value": "NDA", "disabled": false},
    {"value": "Maintenance Contract", "disabled": false},
    {"value": "Partnership Agreement", "disabled": false},
    {"value": "Subcontractor Agreement", "disabled": false},
    {"value": "Other", "disabled": false}
  ]
}'

# Ticket Category
add_options "$TICKET_CATEGORY_ID" "Ticket Category" '{
  "options": [
    {"value": "Bug Report", "disabled": false},
    {"value": "Feature Request", "disabled": false},
    {"value": "How-To Question", "disabled": false},
    {"value": "Integration Issue", "disabled": false},
    {"value": "Performance Issue", "disabled": false},
    {"value": "Billing Question", "disabled": false},
    {"value": "Other", "disabled": false}
  ]
}'

# SLA Priority
add_options "$SLA_PRIORITY_ID" "SLA Priority" '{
  "options": [
    {"value": "Critical (2h response)", "disabled": false},
    {"value": "High (4h response)", "disabled": false},
    {"value": "Medium (8h response)", "disabled": false},
    {"value": "Low (24h response)", "disabled": false}
  ]
}'

# Environment
add_options "$ENVIRONMENT_ID" "Environment" '{
  "options": [
    {"value": "Development", "disabled": false},
    {"value": "Staging", "disabled": false},
    {"value": "Production", "disabled": false}
  ]
}'

echo ""
echo "============================================"
echo "STEP 3: Delete Duplicate Issues from KAN"
echo "============================================"
echo ""
echo "Deleting duplicate tasks (already recreated in proper projects)..."

# Issues to delete (duplicates that were recreated in PROD, MARK, SUPP, OPS)
ISSUES_TO_DELETE=(
  "KAN-1"   # Test issue
  "KAN-6"   # -> PROD-1
  "KAN-7"   # -> PROD-2
  "KAN-8"   # -> PROD-3
  "KAN-9"   # -> PROD-4
  "KAN-10"  # -> MARK-1
  "KAN-11"  # -> MARK-2
  "KAN-12"  # -> MARK-3
  "KAN-13"  # -> MARK-4
  "KAN-14"  # -> SUPP-1
  "KAN-15"  # -> SUPP-2
  "KAN-16"  # -> OPS-1
)

for issue in "${ISSUES_TO_DELETE[@]}"; do
  echo -n "Deleting $issue... "

  RESULT=$(curl -s -w "%{http_code}" -o /dev/null -X DELETE \
    "${JIRA_URL}/rest/api/3/issue/${issue}" \
    -H "Authorization: Basic ${JIRA_AUTH}" \
    -H "Content-Type: application/json")

  if [ "$RESULT" == "204" ]; then
    echo "✓ Deleted"
  else
    echo "⚠️  HTTP $RESULT"
  fi

  sleep 0.3
done

echo ""
echo "============================================"
echo "STEP 4: Verify Results"
echo "============================================"

echo ""
echo "Remaining KAN issues (should be only Epics Q1-Q4):"
curl -s -X GET \
  "${JIRA_URL}/rest/api/3/search?jql=project=KAN&fields=key,summary" \
  -H "Authorization: Basic ${JIRA_AUTH}" \
  -H "Content-Type: application/json" | jq -r '.issues[] | "  \(.key): \(.fields.summary)"'

echo ""
echo "PROD issues:"
curl -s -X GET \
  "${JIRA_URL}/rest/api/3/search?jql=project=PROD&fields=key,summary" \
  -H "Authorization: Basic ${JIRA_AUTH}" \
  -H "Content-Type: application/json" | jq -r '.issues[] | "  \(.key): \(.fields.summary)"'

echo ""
echo "MARK issues:"
curl -s -X GET \
  "${JIRA_URL}/rest/api/3/search?jql=project=MARK&fields=key,summary" \
  -H "Authorization: Basic ${JIRA_AUTH}" \
  -H "Content-Type: application/json" | jq -r '.issues[] | "  \(.key): \(.fields.summary)"'

echo ""
echo "SUPP issues:"
curl -s -X GET \
  "${JIRA_URL}/rest/api/3/search?jql=project=SUPP&fields=key,summary" \
  -H "Authorization: Basic ${JIRA_AUTH}" \
  -H "Content-Type: application/json" | jq -r '.issues[] | "  \(.key): \(.fields.summary)"'

echo ""
echo "OPS issues:"
curl -s -X GET \
  "${JIRA_URL}/rest/api/3/search?jql=project=OPS&fields=key,summary" \
  -H "Authorization: Basic ${JIRA_AUTH}" \
  -H "Content-Type: application/json" | jq -r '.issues[] | "  \(.key): \(.fields.summary)"'

echo ""
echo "============================================"
echo "✅ SETUP COMPLETE!"
echo "============================================"
echo ""
echo "Summary:"
echo "  - Custom field options added"
echo "  - Duplicate KAN issues deleted"
echo "  - KAN now contains only roadmap Epics (Q1-Q4)"
echo "  - Tasks moved to proper projects (PROD, MARK, SUPP, OPS)"
echo ""
echo "Next steps (manual in UI):"
echo "  1. Configure workflows for each project"
echo "  2. Set up automation rules"
echo "  3. Add dashboard gadgets"
echo "  4. Import Odoo contacts to MARK"
