name: Destroy Infra (Terraform, OIDC, Workspaces)

on:
  workflow_dispatch:
    inputs:
      environment:
        description: 'Workspace to destroy (dev|stage|prod)'
        required: true
        default: 'dev'
      destroy_bootstrap:
        description: 'Also destroy bootstrap resources (S3 bucket and DynamoDB table) - USE WITH EXTREME CAUTION'
        required: false
        default: false
        type: boolean

jobs:
  destroy:
    runs-on: ubuntu-latest

    permissions:
      contents: read

    env:
      AWS_REGION: ${{ vars.AWS_REGION || 'us-east-1' }}
      TF_IN_AUTOMATION: "true"

    steps:
      - name: Checkout
        uses: actions/checkout@v4

      - name: Setup Terraform
        uses: hashicorp/setup-terraform@v3
        with:
          terraform_version: 1.9.5
          terraform_wrapper: false

      # Configure AWS credentials using access keys per company policy
      # Note: Requires AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY repository secrets
      # Security: Ensure access keys follow principle of least privilege and key rotation policies
      - name: Configure AWS credentials
        uses: aws-actions/configure-aws-credentials@v4
        with:
          aws-access-key-id: ${{ secrets.DATA_AWS_ACCESS_KEY_ID }}
          aws-secret-access-key: ${{ secrets.DATA_AWS_SECRET_ACCESS_KEY }}
          aws-region: ${{ env.AWS_REGION }}

      - name: Terraform Init (Main Infrastructure)
        working-directory: infra
        run: terraform init -input=false

      - name: Select Workspace and Validate
        working-directory: infra
        run: |
          set -euo pipefail

          WS="${{ github.event.inputs.environment }}"
          echo "Checking for existing Terraform workspace '${WS}'..."

          # Verify backend is initialized
          if [ ! -d .terraform ]; then
            echo "Terraform not initialized yet; running 'terraform init'..."
            terraform init -input=false
          fi

          # Check if workspace exists - abort if not (don't create for destroy)
          if terraform workspace list | sed 's/^[* ]*//' | grep -Fxq "$WS"; then
            echo "Selecting existing workspace: $WS"
            terraform workspace select "$WS"
          else
            echo "❌ ERROR: Workspace '$WS' does not exist. Cannot destroy non-existent workspace."
            echo "Available workspaces:"
            terraform workspace list
            exit 1
          fi

          echo "✅ Workspace '$WS' validated and selected."

      - name: Terraform Destroy Plan
        working-directory: infra
        run: |
          echo "🔍 Generating destroy plan for audit..."
          terraform plan -destroy -input=false -out=destroy.tfplan
          echo "✅ Destroy plan generated. Proceeding with destroy..."

      - name: Terraform Destroy (Main Infrastructure)
        working-directory: infra
        run: terraform destroy -input=false -auto-approve

      - name: Destroy Bootstrap Resources
        if: github.event.inputs.destroy_bootstrap == 'true'
        working-directory: infra/bootstrap
        run: |
          echo "⚠️  WARNING: Destroying bootstrap resources (S3 bucket and DynamoDB table)"
          echo "This will remove the Terraform state storage and could cause data loss!"
          
          # Initialize bootstrap Terraform
          terraform init -input=false
          
          # Check if state bucket is empty (except for our state files)
          BUCKET_NAME="aimodelshare-tfstate-prod-copilot-2024"
          OBJECT_COUNT=$(aws s3api list-objects-v2 --bucket "$BUCKET_NAME" --query 'Contents | length(@)' --output text 2>/dev/null || echo "0")
          
          # AWS CLI returns 'None' for empty buckets, 'null' if bucket doesn't exist, or a number for non-empty buckets
          if [[ "$OBJECT_COUNT" =~ ^[0-9]+$ ]] && [ "$OBJECT_COUNT" -gt 0 ]; then
            echo "⚠️  S3 bucket contains $OBJECT_COUNT objects. Emptying bucket first..."
            aws s3 rm s3://$BUCKET_NAME --recursive
          else
            echo "✅ S3 bucket is empty or doesn't exist (count: $OBJECT_COUNT), proceeding with destroy..."
          fi
          
          # Destroy bootstrap resources
          terraform destroy -input=false -auto-approve
          
          echo "✅ Bootstrap resources destroyed"
