# Website service — operational commands
# --- Configuration ------------------------------------------------------------

# Load configuration from .env (the same file Compose reads).
ENV_FILE := $(if $(wildcard .env),.env,.env.local)
include $(ENV_FILE)
export

# Variables
IMAGE_URL := $(HOST_CONTAINER)/$(HOST_OWNER)/$(IMAGE_NAME)

# Arguments
override version ?= $(IMAGE_TAG)

# Show help if no target is specified.
.DEFAULT_GOAL := help

# --- Swift package ------------------------------------------------------------

.PHONY: pkg-build
pkg-build: ## Build the Swift package
	@swift build

.PHONY: pkg-release
pkg-release: ## Release the Swift package
	@swift build -c release

.PHONY: pkg-test
pkg-test: ## Run the Swift package tests
	@swift test \
		--disable-xctest \
		--enable-code-coverage \
		--enable-swift-testing \
		--parallel

.PHONY: pkg-clean
pkg-clean: ## Remove the Swift build artifacts
	@swift package clean

.PHONY: pkg-reset
pkg-reset: ## Resets the complete SPM cache/build folder
	@swift package reset

.PHONY: pkg-outdated
pkg-outdated: ## Lists the SPM package dependencies that can be updated
	@swift package update --dry-run

.PHONY: pkg-update
pkg-update: ## Updates the SPM package dependencies
	@swift package update

# --- Local development --------------------------------------------------------

.PHONY: img-build
img-build: ## Build the local dev image
	@docker compose build

.PHONY: img-mount
img-mount: ## Mount the service locally (build if needed)
	@docker compose up --build --detach

.PHONY: img-unmount
img-unmount: ## Unmount and remove the local service
	@docker compose down
	@$(MAKE) img-remove

# --- Registry deployment ------------------------------------------------------

.PHONY: img-release
img-release: ## Build the production (amd64) image, tag with version + latest, push both
	@if [ -z "$(version)" ] || [ "$(version)" = "latest" ]; then \
		echo "Error: 'version' must be an explicit tag — e.g. make img-release version=1.2.3"; \
		exit 1; \
	fi
	@docker build \
		--platform $(IMAGE_PLATFORM) \
		--tag $(IMAGE_URL):$(version) \
		--tag $(IMAGE_URL):latest \
		.
	@echo "${HOST_PASSWORD}" \
		| docker login $(HOST_CONTAINER) \
			--username $(HOST_USER) \
			--password-stdin
	@docker push $(IMAGE_URL):$(version)
	@docker push $(IMAGE_URL):latest
	@docker logout $(HOST_CONTAINER)
	@$(MAKE) img-remove

.PHONY: img-remove
img-remove: # Removes the generated Docker images
	@images="$$(docker image ls --format '{{.Repository}}:{{.Tag}}' | grep '$(IMAGE_NAME)' | awk '{print $$1}')"; \
	if [ -n "$$images" ]; then \
		docker image rm --force $$images; \
	else \
		echo "No '$(IMAGE_NAME)' images to remove."; \
	fi

# --- Meta ---------------------------------------------------------------------

.PHONY: help
help: ## Show available commands
	@grep -hE '^[a-zA-Z_-]+:.*?## .*$$' $(MAKEFILE_LIST) \
		| awk 'BEGIN {FS = ":.*?## "}; {printf "  \033[36m%-12s\033[0m %s\n", $$1, $$2}'
