.PHONY: \
	build run \
	test test-unit test-integration test-coverage \
	lint clean \
	migrate-up migrate-down migrate-status migrate-create \
	mysql-up mysql-down mysql-test mysql-test-quick

VERSION := $(shell go run ../versionctl print)
GIT_COMMIT ?= $(shell git rev-parse --short HEAD 2>/dev/null || printf 'unknown')
BUILD_TIME ?= $(shell date -u +"%Y-%m-%dT%H:%M:%SZ")
GO_LDFLAGS := -X nex/backend/pkg/buildinfo.version=$(VERSION) -X nex/backend/pkg/buildinfo.commit=$(GIT_COMMIT) -X nex/backend/pkg/buildinfo.buildTime=$(BUILD_TIME)

DB_DRIVER ?= sqlite3
DB_DSN ?= $(HOME)/.nex/config.db

ifeq ($(DB_DRIVER),mysql)
GOOSE_DIR := migrations/mysql
GOOSE_DRIVER := mysql
else ifeq ($(DB_DRIVER),sqlite3)
GOOSE_DIR := migrations/sqlite
GOOSE_DRIVER := sqlite3
else
$(error unsupported DB_DRIVER '$(DB_DRIVER)', use sqlite3 or mysql)
endif

build:
	go build -ldflags "$(GO_LDFLAGS)" -o bin/server ./cmd/server

run:
	go run -ldflags "$(GO_LDFLAGS)" ./cmd/server

test:
	go test ./internal/... ./pkg/... ./tests/... ./cmd/server/... -v

test-unit:
	go test ./internal/... ./pkg/... -v

test-integration:
	go test ./tests/... -v

test-coverage:
	go test ./... -coverprofile=coverage.out
	go tool cover -html=coverage.out -o coverage.html
	@printf 'Coverage report generated: backend/coverage.html\n'

lint:
	go tool golangci-lint run ./...

clean:
	rm -rf bin/ coverage.out coverage.html

migrate-up:
	@printf 'Running database migration up...\n'
	goose -dir $(GOOSE_DIR) $(GOOSE_DRIVER) "$(DB_DSN)" up

migrate-down:
	@printf 'Running database migration down...\n'
	goose -dir $(GOOSE_DIR) $(GOOSE_DRIVER) "$(DB_DSN)" down

migrate-status:
	@printf 'Checking database migration status...\n'
	goose -dir $(GOOSE_DIR) $(GOOSE_DRIVER) "$(DB_DSN)" status

migrate-create:
	@printf 'Migration name: '; \
	read name; \
	goose -dir migrations/sqlite create $$name sql; \
	goose -dir migrations/mysql create $$name sql

mysql-up:
	@printf 'Starting MySQL test container...\n'
	cd tests/mysql && docker-compose up -d
	@printf 'Waiting for MySQL to be ready...\n'
	@for i in $$(seq 1 30); do \
		if docker exec nex-mysql-test mysqladmin ping -h localhost -u root -ptestpass --silent 2>/dev/null; then \
			printf 'MySQL is ready\n'; \
			exit 0; \
		fi; \
		printf 'Waiting... (%s/30)\n' $$i; \
		sleep 1; \
	done; \
	printf 'MySQL failed to start\n'; \
	exit 1

mysql-down:
	@printf 'Stopping MySQL test container...\n'
	cd tests/mysql && docker-compose down -v

mysql-test:
	@set -e; \
	$(MAKE) mysql-up; \
	trap '$(MAKE) mysql-down' EXIT; \
	go test -tags=mysql ./tests/mysql/... -v -count=1

mysql-test-quick:
	@printf 'Running MySQL tests without container management...\n'
	go test -tags=mysql ./tests/mysql/... -v -count=1
