name: Deploy SWG resources

run-name: ${{ inputs.EXECUTION_MODE }} ${{ inputs.RESOURCE_TYPE }} on ${{ inputs.ENV_NAME }}

permissions:
  id-token: write
  contents: read
  issues: write

on:
  ### Manual deploy section with workflow_dispatch
  workflow_dispatch:
    inputs:
      ENV_NAME:
        description: Environment to deploy
        type: choice
        required: true
        default: palpatine
        options:
        - ahsoka
        - anakin
        - vader
        - boba
        - jabba
        - rey
        - r2d2
        - palpatine
        - bb8
        - c3po
        - solo
        - staging
        - production
        - production-eu
      RESOURCE_TYPE:
        description: Choose the resource type
        type: choice
        required: true
        default: swg-lambda-fetch-profile
        options:
        - swg-lambda-compute-profile
        - swg-sqs-compute-profile
        - swg-lambda-fetch-profile
        - swg-sqs-fetch-profile
        - subscriptions
        - swg-apigw-rest
      BUILD_FROM_SCRATCH:
        type: boolean
        description: Build lambdas from branch
        default: false
      EXECUTION_MODE:
        description: Do you want to apply or destroy?
        type: choice
        default: plan
        required: true
        options:
        - plan
        - apply
        - destroy

env:
  ENV_NAME: ${{ inputs.ENV_NAME }}
  AWS_REGION: 'us-east-1'
  AWS_SECRET_REGION: 'eu-west-2'
  RESOURCE_TYPE: ${{ inputs.RESOURCE_TYPE }}
  EXECUTION_MODE: ${{ inputs.EXECUTION_MODE }}
  BUILD_NUMBER: ${{ github.run_number }}
  LAMBDA_ROOT_PATH: src
  ENV_FILE_VERSION: ''
  NEXUS_USER: svc.nexus@perimeter81.com
  NODE_VERSION: 20
  COMMAND_ARGS: '--terragrunt-disable-bucket-update'


jobs:
  deploy_infra_resource:
    runs-on: ${{ startsWith(inputs.RESOURCE_TYPE, 'swg-lambda-') && 'prod-action-runner' || 'ubuntu-latest' }}
    environment: ${{ inputs.ENV_NAME }}
    steps:
    - name: Deploy resource
      uses: perimeter-81/actions/actions/terragrunt/deploy_resource_v2@P81-54427-Setup-Private-API-Gatway-Based-on-Open-API
      with:
        ENV_NAME: ${{ inputs.ENV_NAME }}
        WORK_DIR: infra/${{ inputs.RESOURCE_TYPE }}
        EXECUTION_MODE: ${{ inputs.EXECUTION_MODE }}
        SAVE_PLAN: false
        TG_VERSION: ''
        TF_VERSION: ''
        COMMAND_ARGS: ${{ env.COMMAND_ARGS }}
        ADMIN_ROLE: 'false'

  build_and_deploy:
    needs: [deploy_infra_resource]
    if: ${{ contains(inputs.RESOURCE_TYPE, 'lambda') && inputs.EXECUTION_MODE == 'apply' && inputs.BUILD_FROM_SCRATCH }}
    runs-on: ubuntu-22.04
    environment: ${{ inputs.ENV_NAME }}
    steps:
    - name: build and trigger deploy
      uses: perimeter-81/actions/actions/lambdas/build_and_trigger_deploy@main
      env:
        LAMBDA_NAME: ${{ inputs.RESOURCE_TYPE }}
