# Windows local API smoke (PowerShell)
# Prereq: docker compose up -d (mysql + redis + next-app)
# Usage: npm run smoke:api

$ErrorActionPreference = "Stop"
$BaseUrl = "http://localhost:3000"
$Token = "demo-host-token"

$Headers = @{
    Authorization = "Bearer $Token"
    "Content-Type"  = "application/json"
}

$BodyObj = [ordered]@{
    request_id     = [guid]::NewGuid().ToString()
    customer_id    = "CUST_001"
    pickup_address = [ordered]@{
        street                     = "1234 Warehouse Blvd"
        city                       = "Los Angeles"
        state                      = "CA"
        zip                        = "90001"
        place_id                   = "ChIJ_pickup"
        formatted_address          = "1234 Warehouse Blvd, Los Angeles, CA 90001, USA"
        selected_from_suggestions  = $true
    }
    delivery_address = [ordered]@{
        street                     = "5678 Distribution Dr"
        city                       = "Dallas"
        state                      = "TX"
        zip                        = "75201"
        place_id                   = "ChIJ_delivery"
        formatted_address          = "5678 Distribution Dr, Dallas, TX 75201, USA"
        selected_from_suggestions  = $true
    }
    weight       = [ordered]@{ value = 500; unit = "lb" }
    dimensions   = [ordered]@{ length = 48; width = 40; height = 48; unit = "in" }
    pallet_count = 2
    cargo_type   = "general_freight"
}

$Body = $BodyObj | ConvertTo-Json -Depth 6 -Compress

Write-Host "[1/3] Check next-app..."
try {
    Invoke-WebRequest -Uri "$BaseUrl" -Method GET -UseBasicParsing | Out-Null
    Write-Host "      OK: $BaseUrl reachable"
}
catch {
    Write-Host "      FAIL: cannot reach $BaseUrl. Run: docker compose up -d"
    exit 1
}

Write-Host "[2/3] POST /api/quotes..."
try {
    $resp = Invoke-RestMethod -Uri "$BaseUrl/api/quotes" -Method POST -Headers $Headers -Body $Body
}
catch {
    $status = $_.Exception.Response.StatusCode.value__
    if ($status -eq 404) {
        Write-Host "      FAIL: /api/quotes 404 (docker image outdated)."
        Write-Host "      Fix: docker compose build next-app; docker compose up -d next-app"
        Write-Host "      Or:  docker compose stop next-app; npm run dev"
        exit 1
    }
    throw
}

Write-Host "      quote_id=$($resp.data.quote_id) status=$($resp.data.status) source=$($resp.data.source_type)"

if ($resp.data.quote_id) {
    Write-Host "[3/3] GET /api/quotes/$($resp.data.quote_id)..."
    $detail = Invoke-RestMethod -Uri "$BaseUrl/api/quotes/$($resp.data.quote_id)" -Method GET -Headers @{
        Authorization = "Bearer $Token"
    }
    Write-Host "      status=$($detail.data.status)"
}

Write-Host "Done."
