# 只保留會重複打的指令；其餘直接 go / migrate。

.PHONY: build test test-integration gen-api tidy migrate-up migrate-down init seeder \
	start stop restart crawler-install crawler crawler-start crawler-stop crawler-restart

RUNTIME_DIR ?= /tmp/haixun

build:
	go build -o bin/gateway .
	go build -o bin/worker ./cmd/worker
	go build -o bin/init ./cmd/init
	go build -o bin/seeder ./cmd/seeder

test:
	go test ./...

# M1–M5 integration gates
test-integration:
	go test ./internal/module/member/usecase/ ./internal/middleware/ \
		./internal/module/threads/... ./internal/module/job/... ./internal/module/appnotif/... \
		./internal/module/usage/... ./internal/module/ai/... ./internal/module/search/... \
		./internal/module/permission/... ./internal/module/studio/... \
		./internal/module/inspire/... ./internal/module/scout/... \
		./internal/logic/extension/ ./internal/logic/media/ \
		-count=1 -timeout 180s

# 改 generate/api/*.api 後執行；handler 勿手寫
gen-api:
	goctl api go -api generate/api/gateway.api -dir . -style go_zero --home generate/goctl

tidy:
	go mod tidy

# DB：檔案在 generate/database/mongo；需本機已裝 migrate（mongodb tag）
# 例：MONGO_URL=mongodb://127.0.0.1:27017/haixun
MONGO_URL ?= mongodb://127.0.0.1:27017/haixun

migrate-up:
	migrate -path generate/database/mongo -database "$(MONGO_URL)" up

migrate-down:
	migrate -path generate/database/mongo -database "$(MONGO_URL)" down 1

init:
	go run ./cmd/init -f etc/gateway.yaml

seeder:
	go run ./cmd/seeder -f etc/gateway.yaml

crawler-install:
	cd crawler && npm install && npx playwright install --with-deps chromium

# Requires SCOUT_CRAWLER_TOKEN equal to Scout.CrawlerToken in gateway.yaml.
crawler:
	cd crawler && npm run start

# Local service lifecycle. Logs and PID files stay outside the worktree.
start: build
	@mkdir -p "$(RUNTIME_DIR)"
	@nohup "$(CURDIR)/bin/gateway" -f "$(CURDIR)/etc/gateway.yaml" >"$(RUNTIME_DIR)/gateway.log" 2>&1 & printf '%s\n' $$! >"$(RUNTIME_DIR)/gateway.pid"
	@nohup "$(CURDIR)/bin/worker" -f "$(CURDIR)/etc/gateway.yaml" >"$(RUNTIME_DIR)/worker.log" 2>&1 & printf '%s\n' $$! >"$(RUNTIME_DIR)/worker.pid"

stop:
	@for service in gateway worker; do \
		pidfile="$(RUNTIME_DIR)/$$service.pid"; \
		if [ -f "$$pidfile" ] && kill -0 "$$(cat "$$pidfile")" 2>/dev/null; then kill "$$(cat "$$pidfile")"; fi; \
		rm -f "$$pidfile"; \
	done

restart: stop start

# The crawler token must come from the private runtime environment, never this file.
crawler-start:
	@test -n "$(SCOUT_CRAWLER_TOKEN)" || (printf '%s\n' 'SCOUT_CRAWLER_TOKEN is required' >&2; exit 1)
	@mkdir -p "$(RUNTIME_DIR)"
	@cd crawler && SCOUT_CRAWLER_TOKEN="$(SCOUT_CRAWLER_TOKEN)" nohup npm run start >"$(RUNTIME_DIR)/crawler.log" 2>&1 & printf '%s\n' $$! >"$(RUNTIME_DIR)/crawler.pid"

crawler-stop:
	@pidfile="$(RUNTIME_DIR)/crawler.pid"; \
	if [ -f "$$pidfile" ] && kill -0 "$$(cat "$$pidfile")" 2>/dev/null; then kill "$$(cat "$$pidfile")"; fi; \
	rm -f "$$pidfile"

crawler-restart: crawler-stop crawler-start
