SHELL := /bin/bash
.ONESHELL:

COMPOSE_FILE := docker-compose.test.yml
PYTEST := python3 -m pytest -q -o addopts=''

REDIS_URL := redis://localhost:6388/0
POSTGRES_DSN := postgresql://sasi:sasi@localhost:55432/sasi_test

.PHONY: test-redis test-postgres test-all test-interfaces clean _check-deps _check-docker _wait-redis _wait-postgres

_check-deps:
	set -euo pipefail
	command -v python3 >/dev/null
	command -v docker >/dev/null
	docker compose version >/dev/null

_check-docker:
	set -euo pipefail
	docker info >/dev/null

_wait-redis:
	set -euo pipefail
	for i in {1..30}; do
		if docker run --rm --network host redis:7-alpine redis-cli -p 6388 ping >/dev/null 2>&1; then
			exit 0
		fi
		sleep 1
	done
	echo "Redis did not become healthy in time" >&2
	exit 1

_wait-postgres:
	set -euo pipefail
	for i in {1..30}; do
		if docker run --rm --network host postgres:16-alpine pg_isready -h localhost -p 55432 -U sasi -d sasi_test >/dev/null 2>&1; then
			exit 0
		fi
		sleep 1
	done
	echo "Postgres did not become healthy in time" >&2
	exit 1

test-interfaces:
	set -euo pipefail
	$(PYTEST) tests/test_interface_contracts.py

test-redis: _check-deps _check-docker
	set -euo pipefail
	trap 'docker compose -f "$(COMPOSE_FILE)" down -v --remove-orphans >/dev/null 2>&1 || true' EXIT
	docker compose -f "$(COMPOSE_FILE)" up -d redis-test
	$(MAKE) _wait-redis
	SASI_REDIS_URL="$(REDIS_URL)" $(PYTEST) sasi_sdk_storage_redis/tests/test_redis_integration.py

test-postgres: _check-deps _check-docker
	set -euo pipefail
	trap 'docker compose -f "$(COMPOSE_FILE)" down -v --remove-orphans >/dev/null 2>&1 || true' EXIT
	docker compose -f "$(COMPOSE_FILE)" up -d postgres-test
	$(MAKE) _wait-postgres
	SASI_POSTGRES_DSN="$(POSTGRES_DSN)" $(PYTEST) sasi_sdk_storage_postgres/tests/test_postgres_integration.py

test-all: _check-deps _check-docker
	set -euo pipefail
	trap 'docker compose -f "$(COMPOSE_FILE)" down -v --remove-orphans >/dev/null 2>&1 || true' EXIT
	docker compose -f "$(COMPOSE_FILE)" up -d redis-test postgres-test
	$(MAKE) _wait-redis
	$(MAKE) _wait-postgres
	SASI_REDIS_URL="$(REDIS_URL)" $(PYTEST) sasi_sdk_storage_redis/tests/test_redis_integration.py
	SASI_POSTGRES_DSN="$(POSTGRES_DSN)" $(PYTEST) sasi_sdk_storage_postgres/tests/test_postgres_integration.py

clean:
	set -euo pipefail
	docker compose -f "$(COMPOSE_FILE)" down -v --remove-orphans
