param(
  [string]$ProjectPath = $PSScriptRoot.Replace('\tools',''),
  [string]$AccountId = '',
  [string]$CloudflareApiToken = '',
  [string]$TurnKeyName = 'spaceship-turn-key',
  [int]$Ttl = 86400
)

$ErrorActionPreference = 'Stop'

function Read-Required($PromptText) {
  do { $v = Read-Host $PromptText } while ([string]::IsNullOrWhiteSpace($v))
  return $v.Trim()
}

if ([string]::IsNullOrWhiteSpace($AccountId)) { $AccountId = Read-Required 'Paste Cloudflare Account ID' }
if ([string]::IsNullOrWhiteSpace($CloudflareApiToken)) { $CloudflareApiToken = Read-Required 'Paste Cloudflare API token with Calls Write permission' }

$headers = @{
  'Authorization' = "Bearer $CloudflareApiToken"
  'Content-Type' = 'application/json'
}
$body = @{ name = $TurnKeyName } | ConvertTo-Json
$url = "https://api.cloudflare.com/client/v4/accounts/$AccountId/calls/turn_keys"

Write-Host 'Creating Cloudflare Calls TURN key...'
$res = Invoke-RestMethod -Method Post -Uri $url -Headers $headers -Body $body

if (-not $res.success) {
  throw ('Cloudflare API failed: ' + ($res.errors | ConvertTo-Json -Depth 5))
}

$turnKeyId = $res.result.uid
$turnApiToken = $res.result.key

if ([string]::IsNullOrWhiteSpace($turnKeyId) -or [string]::IsNullOrWhiteSpace($turnApiToken)) {
  throw 'Cloudflare response did not include result.uid and result.key.'
}

$configureScript = Join-Path $PSScriptRoot 'configure_cloudflare_turn.ps1'
& $configureScript -ProjectPath $ProjectPath -TurnKeyId $turnKeyId -TurnApiToken $turnApiToken -Ttl $Ttl

Write-Host ''
Write-Host 'Cloudflare TURN key was created and saved into api/config.php.' -ForegroundColor Green
Write-Host "TURN Key ID: $turnKeyId"
Write-Host 'TURN API token/key is stored in api/config.php and was not printed again.'
