name: Validate Bicep Solution Versioning

on:
  pull_request:
    branches: [ "main" ]
    paths:
      - '**/metadata.json'
      - '**/CHANGELOG.md'
      - '**/*.bicep'
      - '**/*.bicepparam'
  workflow_dispatch:

permissions:
  contents: read
  pull-requests: write

jobs:
  validate-versioning:
    runs-on: ubuntu-latest
    name: Validate Version Consistency
    
    steps:
      - name: Checkout code
        uses: actions/checkout@v3
        with:
          fetch-depth: 0  # Fetch all history for proper diff
          ref: ${{ github.event.pull_request.head.ref }}

      - name: Setup Git for comparison
        run: |
          git config --global user.name "github-actions[bot]"
          git config --global user.email "github-actions[bot]@users.noreply.github.com"
          git fetch origin ${{ github.base_ref }}
          echo "✅ Git configured and base branch fetched"

      - name: Install dependencies
        run: |
          echo "📦 Installing required dependencies..."
          sudo apt-get update -qq
          sudo apt-get install -y jq
          echo "✅ Dependencies installed"
          echo "   jq version: $(jq --version)"
          echo "   bash version: $BASH_VERSION"

      - name: Verify script exists
        run: |
          if [ ! -f .github/scripts/validate-versioning.sh ]; then
            echo "❌ ERROR: validate-versioning.sh not found"
            exit 1
          fi
          echo "✅ Validation script found"

      - name: Make validation script executable
        run: chmod +x .github/scripts/validate-versioning.sh

      - name: Run versioning validation
        id: validation
        env:
          GITHUB_BASE_REF: ${{ github.base_ref }}
        run: |
          set +e  # Don't exit on error, capture output
          ./.github/scripts/validate-versioning.sh > validation_output.txt 2>&1
          validation_exit_code=$?
          cat validation_output.txt
          echo "exit_code=$validation_exit_code" >> $GITHUB_OUTPUT
          exit $validation_exit_code

      - name: Comment on PR with validation results
        if: always() && github.event_name == 'pull_request'
        uses: actions/github-script@v6
        with:
          script: |
            const fs = require('fs');
            const output = fs.readFileSync('validation_output.txt', 'utf8');
            const exitCode = '${{ steps.validation.outputs.exit_code }}';
            
            let emoji = '✅';
            let title = 'Versioning Validation Passed';
            let color = '28a745';
            
            if (exitCode !== '0') {
              emoji = '❌';
              title = 'Versioning Validation Failed';
              color = 'd73a49';
            } else if (output.includes('WARNING')) {
              emoji = '⚠️';
              title = 'Versioning Validation Passed with Warnings';
              color = 'ffd33d';
            }
            
            const body = `## ${emoji} ${title}
            
            <details>
            <summary>📋 Validation Details</summary>
            
            \`\`\`
            ${output}
            \`\`\`
            
            </details>
            
            ---
            
            ### 📝 Version Consistency Requirements
            
            When updating \`metadata.json\`, ensure:
            
            1. **CHANGELOG.md** contains a section at the top with the new version:
               \`\`\`markdown
               ## X.Y.Z - DD.MM.YYYY
               
               Features(Initials):
               - Description in German
               \`\`\`
            
            2. **Main Bicep file** (alz.bicep or main.bicep) contains matching metadata:
               \`\`\`bicep
               metadata version = 'X.Y.Z'
               \`\`\`
            
            3. **.bicepparam files** in \`configurations/\` folder should reference the latest version:
               \`\`\`bicep
               using 'br:pbagacr1csn.azurecr.io/bicep-solution/{path}:vX.Y.Z'
               \`\`\`
               *(This is a warning - old references will still work but should be updated)*
            `;
            
            // Find existing comment
            const { data: comments } = await github.rest.issues.listComments({
              owner: context.repo.owner,
              repo: context.repo.repo,
              issue_number: context.issue.number,
            });
            
            const botComment = comments.find(comment => 
              comment.user.type === 'Bot' && 
              comment.body.includes('Versioning Validation')
            );
            
            if (botComment) {
              // Update existing comment
              await github.rest.issues.updateComment({
                owner: context.repo.owner,
                repo: context.repo.repo,
                comment_id: botComment.id,
                body: body
              });
            } else {
              // Create new comment
              await github.rest.issues.createComment({
                owner: context.repo.owner,
                repo: context.repo.repo,
                issue_number: context.issue.number,
                body: body
              });
            }

      - name: Upload validation output
        if: always()
        uses: actions/upload-artifact@v4
        with:
          name: validation-output
          path: validation_output.txt
          retention-days: 7
