# Test Epic Creation with Authentication

$apiUrl = "http://localhost:5167"

Write-Host "Step 1: Login to get JWT Token..." -ForegroundColor Cyan

# Login
$loginPayload = @{
    tenantSlug = "testcompany"
    email = "admin@test.com"
    password = "Admin@123456"
} | ConvertTo-Json

$loginResponse = Invoke-RestMethod -Uri "$apiUrl/api/auth/login" -Method Post -Body $loginPayload -ContentType "application/json"
$token = $loginResponse.accessToken
$userId = $loginResponse.user.id

Write-Host "✅ Login successful" -ForegroundColor Green
Write-Host "User ID: $userId" -ForegroundColor Gray
Write-Host "Token (first 50 chars): $($token.Substring(0,50))..." -ForegroundColor Gray
Write-Host ""

Write-Host "Step 2: Create Epic..." -ForegroundColor Cyan

# Create Epic
$projectId = "599e0a24-38be-4ada-945c-2bd11d5b051b"
$createEpicPayload = @{
    projectId = $projectId
    name = "Test Epic from PowerShell"
    description = "This is a test epic created via API"
    priority = "Medium"
    createdBy = $userId
} | ConvertTo-Json

Write-Host "Request Payload:" -ForegroundColor Gray
Write-Host $createEpicPayload -ForegroundColor Gray
Write-Host ""

try {
    $headers = @{
        "Authorization" = "Bearer $token"
        "Content-Type" = "application/json"
    }

    $epicResponse = Invoke-RestMethod -Uri "$apiUrl/api/v1/epics" -Method Post -Body $createEpicPayload -Headers $headers

    Write-Host "✅ Epic created successfully!" -ForegroundColor Green
    Write-Host ""
    Write-Host "Epic Details:" -ForegroundColor Yellow
    $epicResponse | ConvertTo-Json -Depth 3

} catch {
    Write-Host "❌ Failed to create epic" -ForegroundColor Red
    Write-Host "Status Code: $($_.Exception.Response.StatusCode.value__)" -ForegroundColor Red
    Write-Host "Error: $($_.ErrorDetails.Message)" -ForegroundColor Red
}
