# Set GOPATH from `go env`
GOPATH:=$(shell go env GOPATH)
MIGRATIONS_DIR:=./database/migrations
SCHEMA_DIR:=./database/schema
DEV_URL:=docker://postgres/18-alpine/test
DATABASE_URL:=postgres://alinmeuser:password@localhost:5430/alinmedb?sslmode=disable

.PHONY: init test generate buf
init:
	@echo "Initializing project..."
	make buf

buf:
	buf generate --verbose
# Run unit tests
test:
	@echo "Running tests..."
	go test ./... -v

# Generate code using go generate
generate:
	@echo "Running go generate..."
	go generate ./...

env:
	cp -rf ./.env-example  ./.env

lint:
	@ test -e $(LINT) || $(LINT_DOWNLOAD)
	@ $(LINT) --version
	@ $(LINT) run

protoc:
	@ protoc \
  	--go_out=api --go_opt=paths=source_relative \
  	--go-grpc_out=api --go-grpc_opt=paths=source_relative \
  	pb/*.proto

swagger:
	@echo Starting swagger generating
	swag init -g main.go

# Start Postgres in Docker (required before migrate-apply)
docker-up:
	@echo "Starting Postgres in Docker..."
	docker compose up -d pg
	@echo "Waiting for Postgres to be ready..."
	@until docker compose exec pg pg_isready -U alinmeuser -d alinmedb 2>/dev/null; do sleep 1; done
	@echo "Postgres is ready."

# Apply migrations to local Postgres
migrate-apply:
	@echo "Applying migrations..."
	atlas migrate apply --dir "file://$(MIGRATIONS_DIR)" --url "$(DATABASE_URL)"

# Run Docker + migrations (use for local setup)
migrate-local: docker-up migrate-apply
	@echo "Migrations applied successfully."

# Run mock OAuth server for local dev (no Docker - use when testing OAuth flow)
mock-oauth:
	@echo "Starting mock OAuth server on http://localhost:9999"
	go run ./cmd/mock-oauth

migrate-diff:
	@echo "Generating migration diff..."
	atlas migrate diff --dir "file://$(MIGRATIONS_DIR)" --to "file://$(SCHEMA_DIR)" --dev-url "$(DEV_URL)"

# Update atlas.sum with new migration checksums (run after adding migrations)
migrate-hash:
	@echo "Updating migration checksums..."
	atlas migrate hash --dir "file://$(MIGRATIONS_DIR)"
