# Import required modules
using namespace System.Net

# Configuration
$jiraUrl = "https://your-jira-instance"
$username = "your-username"
$password = "your-password"  # Plain password instead of API token
$csvPath = "C:\path\to\your\issues.csv"
$projectKey = "YOUR_PROJECT"

# Create authentication header
$base64AuthInfo = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("${username}:${password}")))
$headers = @{
    Authorization = "Basic $base64AuthInfo"
    "Content-Type" = "application/json"
    Accept = "application/json"
}

# Import CSV
$issues = Import-Csv -Path $csvPath

# Function to create Jira issue
function Create-JiraIssue {
    param (
        [Parameter(Mandatory=$true)]
        [PSCustomObject]$IssueData
    )

    $issueBody = @{
        fields = @{
            project = @{
                key = $projectKey
            }
            summary = $IssueData.Summary
            description = $IssueData.Description
            issuetype = @{
                name = $IssueData.IssueType  # Make sure this matches your Jira issue types
            }
            # Add custom fields if needed
            # customfield_10001 = $IssueData.CustomField
        }
    }

    try {
        $uri = "$jiraUrl/rest/api/2/issue"
        $response = Invoke-RestMethod -Uri $uri -Method Post -Headers $headers -Body ($issueBody | ConvertTo-Json -Depth 10)
        Write-Host "Successfully created issue: $($response.key)" -ForegroundColor Green
        return $response
    }
    catch {
        Write-Host "Error creating issue for: $($IssueData.Summary)" -ForegroundColor Red
        Write-Host "Error: $($_.Exception.Message)" -ForegroundColor Red
        return $null
    }
}

# Initialize counters
$successCount = 0
$failureCount = 0

# Process each issue from CSV
foreach ($issue in $issues) {
    Write-Host "Processing: $($issue.Summary)"
    $result = Create-JiraIssue -IssueData $issue
    
    if ($result) {
        $successCount++
    }
    else {
        $failureCount++
    }
}

# Print summary
Write-Host "`nImport Summary:" -ForegroundColor Cyan
Write-Host "Successfully imported: $successCount issues" -ForegroundColor Green
Write-Host "Failed to import: $failureCount issues" -ForegroundColor Red

# CSV format example (first line of your CSV should have these headers):
# Summary,Description,IssueType
# "Task 1","This is task 1 description","Task"
# "Bug 1","This is a bug description","Bug"
Facebook
Twitter
LinkedIn
Book a call