<#
Simple local CI helper (PowerShell):
- 打包 zip
- 可选上传到上传接口
- 可选触发部署 API
- 可选调用云函数做一次 smoke test

Usage:
  # 只打包
  .\ci-deploy.ps1 -Pack

  # 打包并上传（提供 uploadUrl/uploadToken）
  .\ci-deploy.ps1 -Pack -UploadUrl 'https://your-upload' -UploadToken 'token'

  # 上传后触发部署 API
  .\ci-deploy.ps1 -Pack -UploadUrl 'https://your-upload' -UploadToken 'token' -DeployApi 'https://your-deploy-api' -DeployToken 'token'

#>
param(
  [switch]$Pack,
  [string]$UploadUrl,
  [string]$UploadToken,
  [string]$DeployApi,
  [string]$DeployToken,
  [string]$FuncInvokeUrl,
  [string]$PushToken,
  [string]$TestCid
)

Push-Location (Split-Path -Parent $MyInvocation.MyCommand.Definition)
if ($Pack) {
  Write-Host "Packing cloud function..."
  npm install archiver node-fetch form-data | Out-Null
  node .\deploy-cloudfunc.js
}

if ($UploadUrl) {
  Write-Host "Uploading to $UploadUrl"
  $zip = Join-Path ..\dist testUnipush2.zip
  if (!(Test-Path $zip)) { Write-Error "zip not found: $zip"; exit 2 }
  $headers = @{}
  if ($UploadToken) { $headers.Add('Authorization', "Bearer $UploadToken") }
  $form = @{ file = Get-Item $zip }
  # Use curl.exe for simple multipart upload
  $curlArgs = @('-sS','-X','POST',$UploadUrl)
  if ($UploadToken) { $curlArgs += @('-H',"Authorization: Bearer $UploadToken") }
  $curlArgs += @('-F',"file=@$zip")
  & curl.exe @curlArgs
}

if ($DeployApi) {
  Write-Host "Triggering deploy API: $DeployApi"
  $body = @{ uploadUrl = $UploadUrl } | ConvertTo-Json
  $headers = @()
  if ($DeployToken) { $headers += @('-H',"Authorization: Bearer $DeployToken") }
  & curl.exe -sS -X POST $DeployApi -H 'Content-Type: application/json' $headers -d $body
}

if ($FuncInvokeUrl) {
  Write-Host "Invoking function: $FuncInvokeUrl"
  $payload = @{ token = $PushToken; push_clientid = $TestCid; title='CI Test'; content='hello from CI'; payload = @{} } | ConvertTo-Json
  & curl.exe -sS -X POST $FuncInvokeUrl -H 'Content-Type: application/json' -d $payload
}

Pop-Location
