# Debug script for Project API
$baseUrl = "http://localhost:5167"

# Register tenant
$tenantSlug = "test-project-$(Get-Random -Minimum 1000 -Maximum 9999)"
$registerBody = @{
    tenantName = "Test Project Corp"
    tenantSlug = $tenantSlug
    subscriptionPlan = "Professional"
    adminEmail = "admin@$tenantSlug.com"
    adminPassword = "Admin@1234"
    adminFullName = "Project Admin"
} | ConvertTo-Json

Write-Host "Registering tenant..." -ForegroundColor Yellow
$registerResponse = Invoke-RestMethod -Uri "$baseUrl/api/tenants/register" `
    -Method Post `
    -ContentType "application/json" `
    -Body $registerBody

$token = $registerResponse.accessToken
Write-Host "Token obtained" -ForegroundColor Green
Write-Host ""

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

# Try to create project with detailed error handling
$createProjectBody = @{
    name = "ColaFlow v2.0"
    description = "Test project"
    key = "COLA"
} | ConvertTo-Json

Write-Host "Request Body:" -ForegroundColor Cyan
Write-Host $createProjectBody
Write-Host ""

Write-Host "Creating project..." -ForegroundColor Yellow
try {
    $project = Invoke-RestMethod -Uri "$baseUrl/api/v1/projects" `
        -Method Post `
        -Headers $headers `
        -Body $createProjectBody

    Write-Host "SUCCESS!" -ForegroundColor Green
    Write-Host $project | ConvertTo-Json
} catch {
    Write-Host "ERROR:" -ForegroundColor Red
    Write-Host "Status Code: $($_.Exception.Response.StatusCode.value__)"
    Write-Host "Message: $($_.Exception.Message)"

    if ($_.ErrorDetails) {
        Write-Host "Details:" -ForegroundColor Yellow
        Write-Host $_.ErrorDetails.Message
    }

    # Try to read response body
    if ($_.Exception.Response) {
        $reader = New-Object System.IO.StreamReader($_.Exception.Response.GetResponseStream())
        $reader.BaseStream.Position = 0
        $reader.DiscardBufferedData()
        $responseBody = $reader.ReadToEnd()
        Write-Host "Response Body:" -ForegroundColor Yellow
        Write-Host $responseBody
    }
}
