BINARY  := manager
BIN_DIR := bin
IMG     ?= gateway-cert-operator:dev

# GIT_COMMIT is baked into the image (-ldflags in the Dockerfile); -dirty
# covers staged and untracked changes too, which `git diff --quiet` misses.
GIT_COMMIT ?= $(shell git rev-parse --short=12 HEAD 2>/dev/null || echo unknown)$(shell test -z "$$(git status --porcelain 2>/dev/null)" || echo -dirty)

# golangci-lint type-checks the standard library of whatever toolchain is active,
# and fails on one newer than the Go it was built with. Linting with the go.mod
# version keeps it working when the host Go is ahead, and matches CI.
GO_MOD_VERSION := $(shell awk '$$1 == "go" {print $$2}' go.mod)

.PHONY: all build run test test-short lint vet fmt tidy check docker-build clean help

all: check build

build: ## Build the manager binary to bin/manager
	mkdir -p $(BIN_DIR)
	go build -o $(BIN_DIR)/$(BINARY) .

run: ## Run the manager against the current kubeconfig context
	go run .

test: ## Run the full test suite with the race detector
	go test -race -cover ./...

test-short: ## Run unit tests only — skips tests guarded by testing.Short()
	go test -short -cover ./...

lint: ## Run golangci-lint
	GOTOOLCHAIN=go$(GO_MOD_VERSION) golangci-lint run ./...

vet: ## Run go vet
	go vet ./...

fmt: ## Format all Go files with gofumpt
	gofumpt -w .

tidy: ## Tidy go.mod and go.sum
	go mod tidy

check: lint vet test-short ## Run all quality checks (lint + vet + test-short)

docker-build: ## Build the container image (IMG=name:tag)
	docker build --build-arg GIT_COMMIT=$(GIT_COMMIT) -t $(IMG) .

clean: ## Remove build artifacts
	rm -rf $(BIN_DIR)

help: ## Show available targets
	@echo 'Usage: make <target>'
	@echo ''
	@echo 'Targets:'
	@grep -E '^[a-zA-Z_-]+:.*##' $(MAKEFILE_LIST) | \
		awk 'BEGIN {FS = ":.*## "}; {printf "  \033[36m%-14s\033[0m %s\n", $$1, $$2}'
