IMAGE_NAME=by-other-means
DOCKER_REGISTRY=gitea.pixelparasol.com
DOCKER_WORKSPACE=nathan
DOCKER_TARGET=$(DOCKER_REGISTRY)/$(DOCKER_WORKSPACE)/$(IMAGE_NAME)
K8S_NAMESPACE=by-other-means
TAG := $(shell git rev-parse --short HEAD)
STAMPS := .stamps

.PHONY: all
all:
	@echo "Available targets:"
	@echo "  npm-install     - Force a clean reinstall of npm dependencies"
	@echo "  npm-build       - Build the project (skipped if sources unchanged)"
	@echo "  docker-build    - Build the Docker image (skipped if unchanged)"
	@echo "  docker-push     - Push the Docker image (skipped if already pushed for current commit)"
	@echo "  helm            - Deploy or upgrade the Helm chart (skipped if charts and image unchanged)"

# Force a clean reinstall (explicit use only)
.PHONY: npm-install
npm-install:
	@echo "📦 Installing npm dependencies"
	@rm -rf node_modules
	@npm ci

# Smart install: only runs if package files changed
node_modules/.package-lock.json: package-lock.json package.json
	@echo "📦 Installing npm dependencies"
	@npm ci

$(STAMPS):
	@mkdir -p $@

# Smart build: only runs if source files or deps changed
SRC_FILES := $(shell find src -type f 2>/dev/null)
$(STAMPS)/npm-build: $(SRC_FILES) node_modules/.package-lock.json | $(STAMPS)
	@echo "🏗️  Building the project"
	@npm run build
	@touch $@

.PHONY: npm-build
npm-build: $(STAMPS)/npm-build

# Smart docker build: only runs if npm build or Dockerfile changed, per tag
$(STAMPS)/docker-build-$(TAG): $(STAMPS)/npm-build Dockerfile | $(STAMPS)
	@echo "🐳 Building Docker image $(DOCKER_TARGET):$(TAG)"
	@docker buildx build --no-cache -f Dockerfile . --platform linux/amd64 \
		--load \
		-t $(DOCKER_TARGET):$(TAG) \
		-t $(DOCKER_TARGET):latest
	@touch $@

.PHONY: docker-build
docker-build: $(STAMPS)/docker-build-$(TAG)

# Smart push: only pushes if docker image was (re)built and not yet pushed
$(STAMPS)/docker-pushed-$(TAG): $(STAMPS)/docker-build-$(TAG) | $(STAMPS)
	@echo "🔐 Logging into Docker registry $(DOCKER_REGISTRY)"
	@docker login $(DOCKER_REGISTRY)
	@echo "🚀 Pushing Docker image $(DOCKER_TARGET):$(TAG) and latest"
	@docker push $(DOCKER_TARGET):$(TAG)
	@docker push $(DOCKER_TARGET):latest
	@touch $@

.PHONY: docker-push
docker-push: $(STAMPS)/docker-pushed-$(TAG)

# Smart helm deploy: only runs if chart files changed or a new image was pushed
HELM_FILES := $(shell find helm -type f 2>/dev/null)
$(STAMPS)/helm: $(HELM_FILES) $(STAMPS)/docker-pushed-$(TAG) | $(STAMPS)
	@echo "🚀 Deploying Helm chart to namespace '$(K8S_NAMESPACE)'"
	@helm upgrade --install $(K8S_NAMESPACE) ./helm -n $(K8S_NAMESPACE) --create-namespace
	@touch $@

.PHONY: helm
helm: $(STAMPS)/helm
