PYTHON ?= python3
BASE_URL ?= http://localhost:8080
CA_FILE ?=
ACTION_SCRIPT ?=
TLS_ARGS = $(if $(CA_FILE),--ca-file "$(CA_FILE)",)

.PHONY: help check validate test load test-persistence

help:
	@echo "check: offline structure; validate: full OpenAPI (requirements-dev.txt); test: running API; load: synthetic writes"

check:
	$(PYTHON) scripts/check_contract.py

validate:
	$(PYTHON) scripts/validate_openapi.py

test:
	$(PYTHON) tests/smoke.py --base-url "$(BASE_URL)" $(TLS_ARGS)

load:
	$(PYTHON) tests/load.py --base-url "$(BASE_URL)" $(TLS_ARGS)

test-persistence:
	@test -n "$(ACTION_SCRIPT)" || (echo "Set ACTION_SCRIPT to your implemented executable restart hook"; exit 2)
	$(PYTHON) tests/resilience.py --mode persistence --action-script "$(ACTION_SCRIPT)" --base-url "$(BASE_URL)" $(TLS_ARGS)

# ---------------------------------------------------------------------------
# Application targets (Go implementation). The targets above are the skeleton.
# ---------------------------------------------------------------------------
EVIDENCE_DIR ?= evidence

.PHONY: build vet unit secrets up down destroy logs concurrency explain

build:
	go build -o bin/server ./cmd/server

vet:
	go vet ./...

# The tests start disposable PostgreSQL and Valkey containers: Docker must run.
unit:
	go test -race -count=1 ./...

secrets:
	sh scripts/init-secrets.sh

up:
	docker compose up -d --build --wait

# Stops and removes the containers; volumes and therefore data are kept.
down:
	docker compose down

# Deletes the volumes too: every user, chat, message and session of the stand.
destroy:
	docker compose down -v

logs:
	docker compose logs

concurrency:
	go run ./tools/concurrency --base-url "$(BASE_URL)" --output "$(EVIDENCE_DIR)/concurrency.json"

explain:
	docker compose exec -T postgres psql -U messenger -d messenger -X -q -v ON_ERROR_STOP=1 -f - < scripts/explain-history.sql
