name: Infrastructure Deploy

on:
  workflow_dispatch:
    inputs:
      target_env:
        description: Deploy environment
        required: true
        default: staging
        type: choice
        options:
          - staging
          - production
  release:
    types: [published]

jobs:
  deploy:
    name: Deploy infrastructure + compose
    runs-on: ubuntu-latest
    environment: ${{ github.event_name == 'release' && 'production' || inputs.target_env }}
    permissions:
      contents: read
      id-token: write

    env:
      TARGET_ENV: ${{ github.event_name == 'release' && 'production' || inputs.target_env }}
      TF_STATE_BUCKET: ${{ vars.TF_STATE_BUCKET }}

    steps:
      - uses: actions/checkout@v6

      - name: Authenticate to Google Cloud
        uses: google-github-actions/auth@v3
        with:
          workload_identity_provider: ${{ vars.GCP_WORKLOAD_IDENTITY_PROVIDER }}
          service_account: ${{ vars.GCP_SERVICE_ACCOUNT_EMAIL }}

      - name: Setup gcloud
        uses: google-github-actions/setup-gcloud@v3

      - name: Setup Terraform
        uses: hashicorp/setup-terraform@v4

      - name: Terraform init
        working-directory: infrastructure
        run: |
          if [ -z "${TF_STATE_BUCKET}" ]; then
            echo "Missing repository/environment variable: TF_STATE_BUCKET" >&2
            exit 1
          fi
          terraform init -reconfigure \
            -backend-config="bucket=${TF_STATE_BUCKET}" \
            -backend-config="prefix=hostr/infrastructure/${TARGET_ENV}"

      - name: Terraform apply
        working-directory: infrastructure
        run: |
          terraform apply -auto-approve \
            -var-file=var/shared.tfvars \
            -var-file=var/${TARGET_ENV}.tfvars

      - name: Read Terraform outputs
        id: tfout
        working-directory: infrastructure
        run: |
          echo "project_id=$(terraform output -raw project_id)" >> "$GITHUB_OUTPUT"
          echo "vm_name=$(terraform output -raw compose_vm_name)" >> "$GITHUB_OUTPUT"
          echo "zone=$(terraform output -raw compose_vm_zone)" >> "$GITHUB_OUTPUT"

      - name: Reset VM to trigger compose deploy
        run: |
          gcloud compute instances reset "${{ steps.tfout.outputs.vm_name }}" \
            --project "${{ steps.tfout.outputs.project_id }}" \
            --zone "${{ steps.tfout.outputs.zone }}"
