name: Protected rollback

on:
  workflow_dispatch:
    inputs:
      revision:
        description: Known-good image tag or Git revision
        required: true
        type: string
      environment:
        description: Target environment
        required: true
        default: production
        type: choice
        options: [staging, production]
      confirm:
        description: Type ROLLBACK to continue
        required: true
        type: string

permissions:
  contents: read

jobs:
  validate:
    if: inputs.confirm == 'ROLLBACK'
    runs-on: ubuntu-latest
    steps:
      - run: echo "Rollback approved for ${{ inputs.environment }} to ${{ inputs.revision }}"

  rollback:
    needs: validate
    runs-on: ubuntu-latest
    environment: ${{ inputs.environment }}
    steps:
      - uses: actions/checkout@v4
      - uses: actions/checkout@v4
        with:
          repository: ${{ vars.GITOPS_REPOSITORY }}
          token: ${{ secrets.GITOPS_TOKEN }}
          path: gitops
      - run: node scripts/update-values.mjs "gitops/environments/${{ inputs.environment }}/values.yaml" "${{ inputs.revision }}"
      - working-directory: gitops
        run: |
          git config user.name github-actions[bot]
          git config user.email 41898282+github-actions[bot]@users.noreply.github.com
          git add "environments/${{ inputs.environment }}/values.yaml"
          git commit -m "rollback: ${{ inputs.environment }} to ${{ inputs.revision }}"
          git push
      - run: sleep 30
      - name: Verify recovered application
        run: curl --fail --show-error --retry 10 --retry-all-errors --retry-delay 12 "${{ vars.PRODUCTION_HEALTH_URL }}"
