name: Deploy to Prod

concurrency:
  group: deploy-production
  cancel-in-progress: true

on:
  workflow_dispatch:
    inputs:
      backend_image:
        description: "Backend image tag (full image reference)"
        required: false
      frontend_image:
        description: "Frontend image tag (full image reference)"
        required: false
      apply:
        description: "Apply changes after plan"
        required: false
        default: "true"
  workflow_run:
    workflows: [ "Backend CD", "Frontend CD" ]
    types: [ completed ]

jobs:
  terraform-plan:
    if: ${{ github.event_name != 'workflow_run' || github.event.workflow_run.conclusion == 'success' }}
    runs-on: easynode-debian
    outputs:
      has_changes: ${{ steps.check-changes.outputs.has_changes }}
    permissions:
      contents: read
    steps:
      - name: Checkout code
        uses: actions/checkout@v4
        with:
          fetch-depth: 0

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

      - name: Setup kubectl
        uses: azure/setup-kubectl@v4

      - name: Setup Doppler CLI
        uses: dopplerhq/cli-action@v4

      - name: Setup Kubeconfig
        env:
          DOPPLER_TOKEN: ${{ secrets.DOPPLER_AT_SECRETS }}
        run: |
          mkdir -p ~/.kube
          doppler run --config prd -- bash -c 'echo "$KUBECONFIG_DATA" | base64 -d > ~/.kube/config'
          chmod 600 ~/.kube/config

      - name: Validate cluster access
        run: |
          kubectl cluster-info
          kubectl get namespace tasknote

      - name: Determine deployment values
        id: deploy-vars
        run: |
          backend_image="${{ github.event.inputs.backend_image }}"
          frontend_image="${{ github.event.inputs.frontend_image }}"

          latest_backend_tag="$(git tag --list 'api-v*' | sort -V | tail -n1)"
          echo "latest backend tag=$latest_backend_tag"

          latest_frontend_tag="$(git tag --list 'app-v*' | sort -V | tail -n1)"
          echo "latest frontend tag=$latest_frontend_tag"

          if [ -z "$backend_image" ]; then
            backend_image="docker.io/rmcampos/tasknote-api:$latest_backend_tag"
          fi
          if [ -z "$frontend_image" ]; then
            frontend_image="docker.io/rmcampos/tasknote-app:$latest_frontend_tag"
          fi

          echo "Resolved backend_image=$backend_image"
          echo "Resolved frontend_image=$frontend_image"

          echo "backend_image=$backend_image" >> "$GITHUB_OUTPUT"
          echo "frontend_image=$frontend_image" >> "$GITHUB_OUTPUT"

      - name: Terraform Fmt -check -diff
        working-directory: terraform
        run: terraform fmt -check -diff

      - name: Terraform Init
        working-directory: terraform
        env:
          DOPPLER_TOKEN: ${{ secrets.DOPPLER_AT_SECRETS }}
        run: doppler run --config prd -- terraform init -input=false

      - name: Terraform Validate
        working-directory: terraform
        run: terraform validate

      - name: Terraform Plan
        id: check-changes
        working-directory: terraform
        env:
          DOPPLER_TOKEN: ${{ secrets.DOPPLER_AT_SECRETS }}
          BACKEND_IMAGE: ${{ steps.deploy-vars.outputs.backend_image }}
          FRONTEND_IMAGE: ${{ steps.deploy-vars.outputs.frontend_image }}
        run: |
          doppler run --config prd -- bash -c '
            TF_VAR_db_user="$DB_USER" \
            TF_VAR_db_password="$DB_PASSWORD" \
            TF_VAR_db_name="$DB_NAME" \
            TF_VAR_security_key="$SECURITY_KEY" \
            TF_VAR_mailgun_apikey="$MAILGUN_APIKEY" \
            TF_VAR_r2_access_key="$AWS_ACCESS_KEY_ID" \
            TF_VAR_r2_secret_key="$AWS_SECRET_ACCESS_KEY" \
            TF_VAR_backend_image="$BACKEND_IMAGE" \
            TF_VAR_frontend_image="$FRONTEND_IMAGE" \
            timeout 1m terraform plan -input=false -out=tfplan
          '
          terraform show -json tfplan > tfplan.json
          if jq -e '.resource_changes | length == 0' tfplan.json >/dev/null; then
            echo "has_changes=false" >> "$GITHUB_OUTPUT"
            echo "No changes to apply."
            exit 0
          else
            echo "Changes detected. Proceeding with apply"
            echo "has_changes=true" >> "$GITHUB_OUTPUT"
          fi

      - name: Terraform Apply
        working-directory: terraform
        if: steps.check-changes.outputs.has_changes == 'true'
        env:
          DOPPLER_TOKEN: ${{ secrets.DOPPLER_AT_SECRETS }}
        run: doppler run --config prd -- timeout 2m terraform apply tfplan
