#!/bin/bash

# Week 1 Day 3: Create Custom Fields
# This script will run AFTER projects are created

# Atlassian Cloud credentials (hardcoded for reliable sourcing in SSH contexts)
ATLASSIAN_SITE_URL="https://ai-impress.atlassian.net"
JIRA_AUTH="di5zYW1vaWxlbmtvQGFpLWltcHJlc3MuY29tOkFUQVRUM3hGZkdGMEFCbEppNE1PUkoxTWx5YjZaaFItSTk4NFRZQ3JVaG9HSDN5SGYwYmpoWktrSl9wazI3czZtcmItR1ZvVnRyMGJYbVhXdFlEeVF0MFFMMFV0NkJOcG1mcnoxQVRKbklicUFzV1Z1V2VLSHhxeUtKOGdaVkFwc2k4T0JjLWpDMkJWb0c5VFVFQkRQRE1XbUdfMEpHM3pGVTZidjhqVG1HZWN3ZTJ4bFp6VGlKbz1FMDA5MzE0MA=="

echo "=== Week 1 Day 3: Creating Custom Fields ==="
echo ""
echo "Note: This script runs AFTER projects PROD, MARK, SUPP, OPS are created"
echo ""

# Function to create custom field
create_field() {
    local name=$1
    local type=$2
    local description=$3
    local options=$4

    echo "Creating field: $name ($type)..."

    # Map user-friendly types to Jira API types
    local api_type="$type"
    local api_searcher=""

    case "$type" in
        "select")
            api_type="com.atlassian.jira.plugin.system.customfieldtypes:select"
            api_searcher="com.atlassian.jira.plugin.system.customfieldtypes:multiselectsearcher"
            ;;
        "multiselect")
            api_type="com.atlassian.jira.plugin.system.customfieldtypes:multiselect"
            api_searcher="com.atlassian.jira.plugin.system.customfieldtypes:multiselectsearcher"
            ;;
        "text")
            api_type="com.atlassian.jira.plugin.system.customfieldtypes:textfield"
            api_searcher="com.atlassian.jira.plugin.system.customfieldtypes:textsearcher"
            ;;
        "number")
            api_type="com.atlassian.jira.plugin.system.customfieldtypes:float"
            api_searcher="com.atlassian.jira.plugin.system.customfieldtypes:numberrange"
            ;;
        "date")
            api_type="com.atlassian.jira.plugin.system.customfieldtypes:datepicker"
            api_searcher="com.atlassian.jira.plugin.system.customfieldtypes:daterange"
            ;;
    esac

    local json_data="{\"name\": \"$name\", \"type\": \"$api_type\", \"description\": \"$description\""

    if [ -n "$api_searcher" ]; then
        json_data="$json_data, \"searcherKey\": \"$api_searcher\""
    fi

    json_data="$json_data}"

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

    if grep -q "\"id\":" /tmp/field_response.json; then
        FIELD_ID=$(grep -o '"id":"[^"]*"' /tmp/field_response.json | head -1 | cut -d'"' -f4)
        echo "✓ $name создано (ID: $FIELD_ID)"
    else
        ERROR=$(grep -o '"message":"[^"]*"' /tmp/field_response.json | head -1 | cut -d'"' -f4)
        if [ -z "$ERROR" ]; then
            ERROR=$(cat /tmp/field_response.json | head -c 150)
        fi
        echo "❌ Ошибка: $ERROR"
    fi
    echo ""
}

# PROD Custom Fields (6)
echo "--- PROD Fields ---"
create_field "Client" "select" "Associated client for ticket" '["Internal", "Client Project"]'
create_field "Tech Stack" "multiselect" "Technology stack used" '["Next.js", "React", "Node.js", "PostgreSQL", "n8n", "Docker"]'
create_field "Environment" "select" "Deployment environment" '["Development", "Staging", "Production"]'
create_field "Story Points" "number" "Agile story points"
create_field "Browser" "multiselect" "Browser compatibility" '["Chrome", "Firefox", "Safari", "Edge"]'
create_field "Device" "multiselect" "Device type" '["Desktop", "Mobile", "Tablet"]'

# MARK Custom Fields (8)
echo "--- MARK Fields ---"
create_field "Lead Source" "select" "How we found this lead" '["Website", "Referral", "LinkedIn", "Webinar", "Cold Outreach", "Partner"]'
create_field "Lead Status" "select" "Sales pipeline stage" '["New", "Contacted", "Qualified", "Proposal Sent", "Negotiation", "Won", "Lost"]'
create_field "Company Name" "text" "Company or organization name"
create_field "Contact Email" "text" "Email address"
create_field "Deal Value" "number" "Deal value in pounds"
create_field "Service Package" "select" "Package level" '["Starter", "Growth", "Pro", "Enterprise"]'
create_field "Expected Close Date" "date" "Estimated close date"
create_field "Campaign Type" "select" "Campaign category" '["Webinar", "Content Marketing", "Paid Ads", "Email Campaign", "SEO"]'

# SUPP Custom Fields (3)
echo "--- SUPP Fields ---"
create_field "Priority" "select" "Ticket priority" '["Low", "Medium", "High", "Critical"]'
create_field "Client Account" "select" "Associated client"
create_field "Service" "select" "Service type" '["Webinar Platform", "n8n Automation", "Odoo Consulting", "Website Development", "MarTech Consulting"]'

# OPS Custom Fields (6)
echo "--- OPS Fields ---"
create_field "Category" "select" "Task category" '["HR", "Finance", "Legal", "Compliance", "Admin"]'
create_field "Approval Status" "select" "Approval state" '["Draft", "Pending Review", "Approved", "Rejected"]'
create_field "Invoice Number" "text" "Invoice identifier (INV-YYYY-XXX)"
create_field "Invoice Amount" "number" "Invoice amount in pounds"
create_field "Payment Due Date" "date" "Payment deadline"
create_field "Contract Type" "select" "Contract category" '["MSA", "NDA", "SOW", "Amendment"]'

echo "✓ Custom fields creation complete"
echo ""
echo "Next: Run 05-create-components.sh"
