CONTAINER ?=
COMPOSER_IMAGE ?= composer:2
IMAGE ?= jtl-cloud-php-app-backend
PORT ?= 3005

ifeq ($(CONTAINER),)
COMPOSER := composer
else
COMPOSER := $(CONTAINER) run --rm \
	-v "$(CURDIR)":/app -w /app \
	-e COMPOSER_HOME=/tmp/composer \
	-u "$$(id -u):$$(id -g)" \
	$(COMPOSER_IMAGE)
endif

.PHONY: help install install-dev update shell build run clean test

help:  ## Show this help
	@awk 'BEGIN{FS=":.*##"} /^[a-zA-Z_-]+:.*##/{printf "  %-15s %s\n",$$1,$$2}' $(MAKEFILE_LIST)

install:  ## Install prod dependencies (no dev)
	$(COMPOSER) install --no-dev --no-interaction --prefer-dist

install-dev:  ## Install all dependencies (incl. dev)
	$(COMPOSER) install --no-interaction --prefer-dist

update:  ## Update dependencies
	$(COMPOSER) update --no-interaction

build:  ## Build runtime image (requires CONTAINER=docker or CONTAINER=podman)
ifndef CONTAINER
	$(error CONTAINER is not set — example: CONTAINER=docker make build)
endif
	$(CONTAINER) build -t $(IMAGE) -f Dockerfile .

run: build  ## Run server on PORT (requires CONTAINER=docker or CONTAINER=podman)
	$(CONTAINER) run --rm -p $(PORT):3005 $(if $(wildcard .env),--env-file .env,) $(IMAGE)

shell:  ## Open an interactive shell (containerized when CONTAINER is set)
ifeq ($(CONTAINER),)
	bash
else
	$(CONTAINER) run --rm -it \
		-v "$(CURDIR)":/app -w /app \
		$(COMPOSER_IMAGE) bash
endif

clean:  ## Remove vendor/ and runtime image
	rm -rf vendor/
ifdef CONTAINER
	$(CONTAINER) rmi -f $(IMAGE) 2>/dev/null || true
endif

test:  ## Run PHPUnit (installs dev deps if missing)
	@[ -f vendor/bin/phpunit ] || $(MAKE) install-dev
	$(COMPOSER) exec phpunit
