$auth = Get-Content "$env:USERPROFILE\.ssh\azure_devops_auth.json" -Raw | ConvertFrom-Json
$PAT = $auth.pat
$t = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(":$PAT"))
$h = @{ Authorization = "Basic $t"; 'Content-Type' = 'application/json' }
$base = 'https://dev.azure.com/CN-Squad/Invista%20FIDC%20-%20Nexus/_apis'

# Buscar repo mfe-shell
$repos = Invoke-RestMethod "$base/git/repositories?api-version=7.0" -Headers $h
$repo = $repos.value | Where-Object { $_.name -eq 'mfe-shell' } | Select-Object -First 1
if (-not $repo) { Write-Host "ERRO: repo mfe-shell nao encontrado"; exit 1 }

$repoId = $repo.id
Write-Host "Repo: $($repo.name) id=$repoId"

# Buscar branch devops
$branch = Invoke-RestMethod "$base/git/repositories/$repoId/refs?filter=heads/devops&api-version=7.0" -Headers $h
$sha = $branch.value[0].objectId
Write-Host "Branch devops: $sha"

# Verificar se .trigger-dns existe para usar edit ou add
$items = Invoke-RestMethod "$base/git/repositories/$repoId/items?path=/.trigger-dns&versionDescriptor.versionType=branch&versionDescriptor.version=devops&api-version=7.0" -Headers $h -ErrorAction SilentlyContinue
$changeType = if ($items -and $items.value) { 'edit' } else { 'add' }
Write-Host "Usando changeType: $changeType"

# Push trigger commit
$body = @{
  refUpdates = @(@{ name = 'refs/heads/devops'; oldObjectId = $sha })
  commits = @(@{
    comment = 'chore: retrigger mfe-shell pipeline (dns oci subdomain)'
    changes = @(@{
      changeType = 'edit'
      item = @{ path = '/.trigger-dns' }
      newContent = @{ content = (Get-Date -Format 'yyyy-MM-dd HH:mm:ss'); contentType = 'rawtext' }
    })
  })
} | ConvertTo-Json -Depth 6

$push = Invoke-RestMethod "$base/git/repositories/$repoId/pushes?api-version=7.0" `
  -Method POST -Headers $h -Body $body

Write-Host "Push ID: $($push.pushId)  commit: $($push.commits[0].commitId)"
Write-Host "Pipeline sera triggerada automaticamente."
