name: Terraform Provider Generation

on:
  pull_request:
  push:
    branches:
      - main
      - master
      - develop
  workflow_dispatch: # Allow manual trigger

jobs:
  generate-terraform-provider:
    runs-on: ubuntu-latest
    env:
      CI_PIPELINE_ID: ${{ github.run_number }}
    
    steps:
      - name: Checkout code
        uses: actions/checkout@v4

      - name: Setup Node.js
        uses: actions/setup-node@v4
        with:
          node-version: latest
          cache: 'npm'

      - name: Setup Go
        uses: actions/setup-go@v5
        with:
          go-version: 'stable'
          cache: true

      - name: Install Common dependencies
        run: cd Common && npm install

      - name: Install root dependencies
        run: npm install

      - name: Install Script dependencies
        run: cd Scripts && npm install

      - name: Generate Terraform provider
        run: npm run generate-terraform-provider

      - name: Verify provider generation
        run: |
          PROVIDER_DIR="./Terraform"
          
          # Check if provider directory was created
          if [ ! -d "$PROVIDER_DIR" ]; then
            echo "❌ Terraform provider directory not created"
            exit 1
          fi
          echo "✅ Provider directory created: $PROVIDER_DIR"
          
          # Count generated files
          GO_FILES=$(find "$PROVIDER_DIR" -name "*.go" | wc -l)
          echo "📊 Generated Go files: $GO_FILES"
          
          if [ "$GO_FILES" -eq 0 ]; then
            echo "❌ No Go files were generated"
            exit 1
          fi
          
          # Check for essential files
          if [ -f "$PROVIDER_DIR/go.mod" ]; then
            echo "✅ Go module file created"
          fi
          
          if [ -f "$PROVIDER_DIR/README.md" ]; then
            echo "✅ Documentation created"
          fi
          
          # Show directory structure for debugging
          echo "📁 Provider directory structure:"
          ls -la "$PROVIDER_DIR" || true

      - name: Test Go build
        uses: nick-fields/retry@v3
        with:
          timeout_minutes: 30
          max_attempts: 3
          command: |
            PROVIDER_DIR="./Terraform"
            if [ -d "$PROVIDER_DIR" ] && [ -f "$PROVIDER_DIR/go.mod" ]; then
              cd "$PROVIDER_DIR"
              echo "🔨 Testing Go build..."
              go mod tidy
              go build -v ./...
              echo "✅ Go build successful"
            else
              echo "⚠️ Cannot test build - missing go.mod or provider directory"
            fi

      - name: Upload Terraform provider as artifact
        uses: actions/upload-artifact@v4
        with:
          name: Terraform
          path: ./Terraform/
          retention-days: 30