---
parameters:
  - name: root_module_folder_relative_path
    default: '.'
  - name: terraform_cli_version
    default: 'latest'

stages:
  - stage: validate
    displayName: Validation Terraform
    variables:
      - group: ${variable_group_name}
      - name: 'selfHostedAgent'
        value: '${self_hosted_agent}'
    jobs:
      - job: validate
        displayName: Validate Terraform
        pool:
          ${agent_pool_configuration}
        steps:
          - template: helpers/terraform-installer.yaml
            parameters:
              terraformVersion: $${{ parameters.terraform_cli_version }}
          - pwsh: |
              terraform `
              -chdir="$${{ parameters.root_module_folder_relative_path }}" `
              fmt `
              -check
            displayName: Terraform Format Check
          - pwsh: |
              terraform `
              -chdir="$${{ parameters.root_module_folder_relative_path }}" `
              init `
              -backend=false
            displayName: Terraform Init
          - pwsh: |
              terraform `
              -chdir="$${{ parameters.root_module_folder_relative_path }}" `
              validate
            displayName: Terraform Validate
      - deployment: plan
        dependsOn: validate
        displayName: Validate Terraform Plan
        pool:
          ${agent_pool_configuration}
        environment: ${environment_name_plan}
        timeoutInMinutes: 0
        strategy:
          runOnce:
            deploy:
              steps:
                - checkout: self
                  displayName: Checkout Terraform Module
                - template: helpers/terraform-installer.yaml
                  parameters:
                    terraformVersion: $${{ parameters.terraform_cli_version }}
                - template: helpers/terraform-init.yaml
                  parameters:
                    serviceConnection: '${service_connection_name_plan}'
                    backendAzureResourceGroupName: $(BACKEND_AZURE_RESOURCE_GROUP_NAME)
                    backendAzureStorageAccountName: $(BACKEND_AZURE_STORAGE_ACCOUNT_NAME)
                    backendAzureStorageAccountContainerName: $(BACKEND_AZURE_STORAGE_ACCOUNT_CONTAINER_NAME)
                    root_module_folder_relative_path: $${{ parameters.root_module_folder_relative_path }}
                - template: helpers/terraform-plan.yaml
                  parameters:
                    serviceConnection: '${service_connection_name_plan}'
                    root_module_folder_relative_path: $${{ parameters.root_module_folder_relative_path }}
