.PHONY: build run test test-integration clean version help

# Version information
VERSION := $(shell git describe --tags --always --dirty 2>/dev/null || echo "dev")
BUILD_TIME := $(shell date -u '+%Y-%m-%d_%H:%M:%S')
GIT_COMMIT := $(shell git rev-parse HEAD 2>/dev/null || echo "unknown")
GIT_BRANCH := $(shell git rev-parse --abbrev-ref HEAD 2>/dev/null || echo "unknown")

# Build flags
LDFLAGS := -ldflags "\
	-X main.version=$(VERSION) \
	-X main.buildTime=$(BUILD_TIME) \
	-X main.gitCommit=$(GIT_COMMIT)"

# Default target
help:
	@echo "Available targets:"
	@echo "  build              - Build the application"
	@echo "  run                - Run the application"
	@echo "  test               - Run unit tests"
	@echo "  test-integration   - Run integration tests"
	@echo "  test-all           - Run all tests"
	@echo "  clean              - Clean build artifacts"
	@echo "  version            - Show version information"
	@echo ""
	@echo "Build with custom tags:"
	@echo "  make build TAGS=dev"
	@echo "  make run TAGS=dev"

# Build the application
build:
	@echo "Building..."
	@go build $(LDFLAGS) $(if $(TAGS),-tags $(TAGS)) -o bin/myapp .

# Run the application
run:
	@echo "Running..."
	@go run $(if $(TAGS),-tags $(TAGS)) .

# Run unit tests (excluding integration tests)
test:
	@echo "Running unit tests..."
	@go test -v -race -coverprofile=coverage.out ./...

# Run integration tests
test-integration:
	@echo "Running integration tests..."
	@go test -v -race -tags integration ./...

# Run all tests
test-all: test test-integration

# Run tests with goleak
test-leak:
	@echo "Running tests with leak detection..."
	@go test -v -race ./...

# Clean build artifacts
clean:
	@echo "Cleaning..."
	@rm -rf bin/ tmp/
	@go clean

# Show version information
version:
	@echo "Version:     $(VERSION)"
	@echo "Build Time:  $(BUILD_TIME)"
	@echo "Git Commit:  $(GIT_COMMIT)"
	@echo "Git Branch:  $(GIT_BRANCH)"

# Install development tools
install-tools:
	@echo "Installing development tools..."
	@go install github.com/cosmtrek/air@latest
	@go install go.uber.org/goleak@latest
	@go install golang.org/x/tools/go/analysis/passes/fieldalignment/cmd/fieldalignment@latest
	@echo "Tools installed successfully!"
