# fix_mfe_pipelines_oci.ps1
# Atualiza azure-pipelines.yml na branch devops de cada MFE repo para usar
# o novo template deploy-mfe-oci.yaml (OCI Object Storage).
#
# Uso: ./fix_mfe_pipelines_oci.ps1
# Requer: PAT com permissao Code (Read & Write) no Azure DevOps

$pat  = '19mNqNXIoZ4c3EriFNfzfkgpGNOvLjpOqqZnTFXKnzjxWJ5zURjgJQQJ99CBACAAAAAamI5kAAASAZDOAMPp'
$tok  = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(':' + $pat))
$h    = @{ Authorization = 'Basic ' + $tok; 'Content-Type' = 'application/json' }
$base = 'https://dev.azure.com/CN-Squad/Invista%20FIDC%20-%20Nexus/_apis'

# Configuracao dos MFEs: nome do repo -> parametros do template
$mfe_config = [ordered]@{
  'mfe-shell'  = @{ mfeName = 'mfe-shell';  isShell = $true  }
  'mfe-auth'   = @{ mfeName = 'mfe-auth';   isShell = $false }
  'mfe-user'   = @{ mfeName = 'mfe-user';   isShell = $false }
  'mfe-person' = @{ mfeName = 'mfe-person'; isShell = $false }
  'mfe-poc'    = @{ mfeName = 'mfe-poc';    isShell = $false }
}

# Buscar todos os repos do projeto
Write-Host "Buscando repositorios..." -ForegroundColor Cyan
$repos = Invoke-RestMethod -Uri "$base/git/repositories?api-version=7.0" -Headers $h
$repo_map = @{}
foreach ($r in $repos.value) {
  $repo_map[$r.name] = $r.id
}

foreach ($mfe_name in $mfe_config.Keys) {
  $cfg     = $mfe_config[$mfe_name]
  $repoId  = $repo_map[$mfe_name]
  $isShell = if ($cfg.isShell) { 'true' } else { 'false' }

  Write-Host ""
  Write-Host "=== $mfe_name ===" -ForegroundColor Cyan

  if (-not $repoId) {
    Write-Host "  AVISO: repo '$mfe_name' nao encontrado no Azure DevOps. Pulando." -ForegroundColor Yellow
    continue
  }
  Write-Host "  Repo ID: $repoId"

  # 1. Verificar se branch devops existe
  $ref = Invoke-RestMethod -Uri "$base/git/repositories/$repoId/refs?filter=heads/devops&api-version=7.0" -Headers $h
  if ($ref.count -eq 0) {
    Write-Host "  AVISO: branch devops nao encontrada. Pulando." -ForegroundColor Yellow
    continue
  }
  $oldSha = $ref.value[0].objectId
  Write-Host "  SHA devops: $oldSha"

  # 2. Verificar se azure-pipelines.yml existe na branch devops
  $fileExists = $true
  try {
    $current = Invoke-RestMethod `
      -Uri "$base/git/repositories/$repoId/items?path=/azure-pipelines.yml&versionDescriptor.version=devops&api-version=7.0" `
      -Headers $h -ErrorAction Stop
  } catch {
    $fileExists = $false
    Write-Host "  azure-pipelines.yml nao existe na branch devops (sera criado)."
  }

  # 3. Montar novo conteudo do pipeline
  $newContent = @"
trigger:
  branches:
    include:
      - devops

resources:
  repositories:
    - repository: templates
      type: git
      name: azure-pipelines-templates
      ref: refs/heads/main

extends:
  template: mfe/deploy-mfe-oci.yaml@templates
  parameters:
    mfeName: '$($cfg.mfeName)'
    envName: 'dev'
    isShell: $isShell
"@

  # 4. Nao atualizar se conteudo identico
  if ($fileExists -and $current -eq $newContent) {
    Write-Host "  Sem alteracoes necessarias." -ForegroundColor Yellow
    continue
  }

  # 5. Push para branch devops
  $changeType = if ($fileExists) { 'edit' } else { 'add' }
  $body = @{
    refUpdates = @(@{ name = 'refs/heads/devops'; oldObjectId = $oldSha })
    commits    = @(@{
      comment = "feat(pipeline): migrar $mfe_name para deploy OCI Object Storage via template"
      changes = @(@{
        changeType = $changeType
        item       = @{ path = '/azure-pipelines.yml' }
        newContent = @{ content = $newContent; contentType = 'rawtext' }
      })
    })
  } | ConvertTo-Json -Depth 10

  try {
    $result = Invoke-RestMethod `
      -Uri "$base/git/repositories/$repoId/pushes?api-version=7.0" `
      -Method POST -Headers $h -Body $body -ErrorAction Stop
    Write-Host "  OK - commit: $($result.commits[0].commitId)" -ForegroundColor Green
  } catch {
    Write-Host "  ERRO ao fazer push: $_" -ForegroundColor Red
  }
}

Write-Host ""
Write-Host "Concluido." -ForegroundColor Green
