name: terraform-dev

on:
  pull_request:
    paths:
      - "environments/dev/Seahorse/**"
      - "environments/modules/**"
      - ".gitea/workflows/terraform-dev.yml"
  push:
    branches:
      - main
    paths:
      - "environments/dev/Seahorse/**"
      - "environments/modules/**"
      - ".gitea/workflows/terraform-dev.yml"
  workflow_dispatch:
    inputs:
      run_apply:
        description: "Run terraform apply (true/false)"
        required: true
        default: "false"

env:
  TF_IN_AUTOMATION: "true"
  TF_INPUT: "false"
  TF_CLI_ARGS_init: "-backend=false"
  WORKDIR: "environments/dev/Seahorse"

jobs:
  validate:
    runs-on: [terraform-host]
    steps:
      - name: Checkout
        uses: actions/checkout@v4

      - name: Terraform version
        run: terraform version

      - name: Terraform fmt check
        run: terraform fmt -check -recursive

      - name: Terraform init (no backend)
        working-directory: ${{ env.WORKDIR }}
        env:
          VAULT_ADDR: ${{ secrets.VAULT_ADDR }}
          VAULT_TOKEN: ${{ secrets.VAULT_TOKEN }}
        run: terraform init

      - name: Terraform validate
        working-directory: ${{ env.WORKDIR }}
        env:
          VAULT_ADDR: ${{ secrets.VAULT_ADDR }}
          VAULT_TOKEN: ${{ secrets.VAULT_TOKEN }}
        run: terraform validate

  plan:
    needs: validate
    runs-on: [terraform-host]
    steps:
      - name: Checkout
        uses: actions/checkout@v4

      - name: Terraform init (no backend)
        working-directory: ${{ env.WORKDIR }}
        env:
          VAULT_ADDR: ${{ secrets.VAULT_ADDR }}
          VAULT_TOKEN: ${{ secrets.VAULT_TOKEN }}
        run: terraform init

      - name: Terraform plan
        working-directory: ${{ env.WORKDIR }}
        env:
          VAULT_ADDR: ${{ secrets.VAULT_ADDR }}
          VAULT_TOKEN: ${{ secrets.VAULT_TOKEN }}
        run: terraform plan -refresh=false -lock=false -out=tfplan

  apply:
    if: github.event_name == 'workflow_dispatch' && github.event.inputs.run_apply == 'true'
    needs: plan
    runs-on: [terraform-host]
    steps:
      - name: Checkout
        uses: actions/checkout@v4

      - name: Terraform init (no backend)
        working-directory: ${{ env.WORKDIR }}
        env:
          VAULT_ADDR: ${{ secrets.VAULT_ADDR }}
          VAULT_TOKEN: ${{ secrets.VAULT_TOKEN }}
        run: terraform init

      - name: Terraform apply (manual trigger)
        working-directory: ${{ env.WORKDIR }}
        env:
          VAULT_ADDR: ${{ secrets.VAULT_ADDR }}
          VAULT_TOKEN: ${{ secrets.VAULT_TOKEN }}
        run: terraform apply -refresh=false -lock=false -auto-approve