name: Validate CRD Generation

# This workflow validates that generated CRD files are up-to-date when tool
# dependencies change. It ensures that if go.tool.mod or go.tool.sum are updated,
# the corresponding generated files (CRDs and deepcopy code) are also regenerated
# and committed in the same PR.
#
# Why this is needed:
# - controller-gen (from go.tool.mod) generates CRD YAML and deepcopy Go code
# - Different versions of controller-gen may produce different output
# - When tool versions change, generated code must be regenerated
# - This prevents CI failures and runtime issues from stale generated code

on:
  pull_request:
    paths:
      - 'go.tool.mod'
      - 'go.tool.sum'
      - 'scripts/generate-crd.sh'
      - '**/dnsendpoints.externaldns.k8s.io.yaml'

permissions:
  contents: read

jobs:
  validate-crd:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout repository
        uses: actions/checkout@8e8c483db84b4bee98b60c0593521ed34d9990e8 # v6.0.1

      - name: Set up Go
        uses: actions/setup-go@def8c394e3ad351a79bc93815e4a585520fe993b # v6.2.0
        with:
          go-version-file: 'go.mod'

      - name: Regenerate CRDs
        run: ./scripts/generate-crd.sh

      - name: Check for uncommitted changes
        id: check_changes
        run: |
          # Check if there are any changes to generated files
          if ! git diff --quiet; then
            echo "::error::Generated CRD files are out of sync with go.tool.mod"
            echo ""
            echo "The following files have uncommitted changes after running 'make crd':"
            git diff .
            echo ""
            echo "This usually means:"
            echo "1. go.tool.mod or go.tool.sum was updated (new controller-gen version)"
            echo "2. The generated CRD files were not regenerated"
            echo ""
            echo "To fix this:"
            echo "  make crd"
            echo "  git diff ."
            echo "  commit, push and update your PR:"
            exit 1
          fi

      - name: Success
        if: success()
        run: |
          echo "✅ Generated CRD files are up-to-date"
