# Invoice Navigator - E-Invoice Validation GitHub Action
# Validate your e-invoices in CI/CD pipelines
#
# Usage:
#   1. Copy this file to .github/workflows/validate-invoices.yml
#   2. Add INVOICE_NAV_API_KEY to your repository secrets
#   3. Customize the invoice_path to match your invoice location
#
# Documentation: https://www.invoicenavigator.eu/developers
# Get API Key: https://www.invoicenavigator.eu/signup?redirect=/dashboard/api
#   (try first without an account: curl -X POST https://www.invoicenavigator.eu/api/developers/instant-key)

name: Validate E-Invoices

on:
  push:
    paths:
      - 'invoices/**/*.xml'
      - '.github/workflows/validate-invoices.yml'
  pull_request:
    paths:
      - 'invoices/**/*.xml'
  workflow_dispatch:
    inputs:
      invoice_path:
        description: 'Path to invoice file or directory'
        required: false
        default: 'invoices'

env:
  INVOICE_NAV_API_URL: https://www.invoicenavigator.eu/api/v2

jobs:
  validate:
    name: Validate Invoices
    runs-on: ubuntu-latest

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

      - name: Find invoice files
        id: find-invoices
        run: |
          INVOICE_PATH="${{ github.event.inputs.invoice_path || 'invoices' }}"
          if [ -d "$INVOICE_PATH" ]; then
            FILES=$(find "$INVOICE_PATH" -name "*.xml" -type f | tr '\n' ' ')
          else
            FILES="$INVOICE_PATH"
          fi
          echo "files=$FILES" >> $GITHUB_OUTPUT
          echo "Found invoice files: $FILES"

      - name: Validate invoices
        id: validate
        env:
          INVOICE_NAV_API_KEY: ${{ secrets.INVOICE_NAV_API_KEY }}
        run: |
          set -e

          RESULTS_FILE="validation-results.json"
          echo "[]" > "$RESULTS_FILE"

          TOTAL=0
          PASSED=0
          FAILED=0

          for FILE in ${{ steps.find-invoices.outputs.files }}; do
            if [ -f "$FILE" ]; then
              echo "Validating: $FILE"
              TOTAL=$((TOTAL + 1))

              # Call the API
              RESPONSE=$(curl -s -X POST "$INVOICE_NAV_API_URL/validate" \
                -H "Authorization: Bearer $INVOICE_NAV_API_KEY" \
                -H "Content-Type: application/json" \
                -d "{\"xml\": $(cat "$FILE" | jq -Rs .)}")

              # v2 envelope: { success, data: { isValid, issues[] } } — errors only, warnings don't fail
              IS_VALID=$(echo "$RESPONSE" | jq -r '.data.isValid // false')
              ERROR_COUNT=$(echo "$RESPONSE" | jq -r '[.data.issues[]? | select(.severity == "error")] | length')
              if [ "$(echo "$RESPONSE" | jq -r '.success // false')" != "true" ]; then
                echo "::error::API error: $(echo "$RESPONSE" | jq -r '.error.code // "UNKNOWN"') — $(echo "$RESPONSE" | jq -r '.error.message // empty')"
              fi

              if [ "$IS_VALID" = "true" ]; then
                echo "✅ $FILE: Valid"
                PASSED=$((PASSED + 1))
              else
                echo "❌ $FILE: Invalid ($ERROR_COUNT errors)"
                echo "$RESPONSE" | jq -r '.data.issues[]? | select(.severity == "error") | "   - [\(.code)] \(.message)"'
                FAILED=$((FAILED + 1))
              fi

              # Append to results
              echo "$RESPONSE" | jq --arg file "$FILE" '. + {file: $file}' >> "$RESULTS_FILE.tmp"
              jq -s '.' "$RESULTS_FILE.tmp" > "$RESULTS_FILE" 2>/dev/null || true
            fi
          done

          echo ""
          echo "=========================================="
          echo "Validation Summary"
          echo "=========================================="
          echo "Total:  $TOTAL"
          echo "Passed: $PASSED"
          echo "Failed: $FAILED"
          echo "=========================================="

          echo "total=$TOTAL" >> $GITHUB_OUTPUT
          echo "passed=$PASSED" >> $GITHUB_OUTPUT
          echo "failed=$FAILED" >> $GITHUB_OUTPUT

          # Fail the job if any invoices are invalid
          if [ $FAILED -gt 0 ]; then
            echo "::error::$FAILED invoice(s) failed validation"
            exit 1
          fi

      - name: Upload validation results
        if: always()
        uses: actions/upload-artifact@v4
        with:
          name: validation-results
          path: validation-results.json
          retention-days: 30

      - name: Post PR comment
        if: github.event_name == 'pull_request' && always()
        uses: actions/github-script@v7
        with:
          script: |
            const total = '${{ steps.validate.outputs.total }}';
            const passed = '${{ steps.validate.outputs.passed }}';
            const failed = '${{ steps.validate.outputs.failed }}';

            const status = failed === '0' ? '✅' : '❌';
            const body = `## ${status} E-Invoice Validation Results

            | Metric | Count |
            |--------|-------|
            | Total invoices | ${total} |
            | ✅ Passed | ${passed} |
            | ❌ Failed | ${failed} |

            ${failed !== '0' ? '⚠️ Some invoices failed validation. Check the workflow logs for details.' : '🎉 All invoices are valid!'}

            ---
            *Powered by [Invoice Navigator](https://www.invoicenavigator.eu)*`;

            github.rest.issues.createComment({
              issue_number: context.issue.number,
              owner: context.repo.owner,
              repo: context.repo.repo,
              body: body
            });

      - name: Set job summary
        if: always()
        run: |
          echo "## E-Invoice Validation Results" >> $GITHUB_STEP_SUMMARY
          echo "" >> $GITHUB_STEP_SUMMARY
          echo "| Metric | Count |" >> $GITHUB_STEP_SUMMARY
          echo "|--------|-------|" >> $GITHUB_STEP_SUMMARY
          echo "| Total invoices | ${{ steps.validate.outputs.total }} |" >> $GITHUB_STEP_SUMMARY
          echo "| ✅ Passed | ${{ steps.validate.outputs.passed }} |" >> $GITHUB_STEP_SUMMARY
          echo "| ❌ Failed | ${{ steps.validate.outputs.failed }} |" >> $GITHUB_STEP_SUMMARY
          echo "" >> $GITHUB_STEP_SUMMARY
          echo "---" >> $GITHUB_STEP_SUMMARY
          echo "*Powered by [Invoice Navigator](https://www.invoicenavigator.eu)*" >> $GITHUB_STEP_SUMMARY
