# Test Bug Fix - Tenant Registration
$body = @{
    tenantName = "BugFix Test Corp"
    tenantSlug = "bugfix-test-$(Get-Random)"
    subscriptionPlan = "Professional"
    adminEmail = "admin@bugfix$(Get-Random).com"
    adminPassword = "Admin@1234"
    adminFullName = "Bug Fix Admin"
} | ConvertTo-Json

Write-Host "Testing Tenant Registration..."
Write-Host "Endpoint: http://localhost:5167/api/tenants/register"

try {
    $response = Invoke-RestMethod -Uri "http://localhost:5167/api/tenants/register" `
        -Method Post `
        -ContentType "application/json" `
        -Body $body `
        -ErrorAction Stop

    Write-Host ""
    Write-Host "==================================" -ForegroundColor Green
    Write-Host "SUCCESS - BUG FIXED!" -ForegroundColor Green
    Write-Host "==================================" -ForegroundColor Green
    Write-Host ""
    Write-Host "Tenant Name: $($response.tenantName)" -ForegroundColor Cyan
    Write-Host "Tenant Slug: $($response.tenantSlug)" -ForegroundColor Cyan
    Write-Host "User Email: $($response.user.email)" -ForegroundColor Cyan
    Write-Host "User Role: $($response.user.role)" -ForegroundColor Cyan
    Write-Host "Access Token: $($response.accessToken.Substring(0, 50))..." -ForegroundColor Yellow
    Write-Host "Refresh Token: $($response.refreshToken.Substring(0, 50))..." -ForegroundColor Yellow
    Write-Host ""
    Write-Host "The foreign key constraint bug has been successfully fixed!" -ForegroundColor Green
    exit 0
} catch {
    Write-Host ""
    Write-Host "==================================" -ForegroundColor Red
    Write-Host "FAILURE - Bug Still Exists" -ForegroundColor Red
    Write-Host "==================================" -ForegroundColor Red
    Write-Host ""
    Write-Host "Error: $($_.Exception.Message)" -ForegroundColor Red
    Write-Host ""
    if ($_.Exception.Response) {
        $reader = New-Object System.IO.StreamReader($_.Exception.Response.GetResponseStream())
        $responseBody = $reader.ReadToEnd()
        Write-Host "Response: $responseBody" -ForegroundColor Yellow
    }
    exit 1
}
