GO ?= go
GOFMT ?= gofmt
GOCTL ?= goctl
GO_ZERO_STYLE := go_zero
API_ENTRY := ./generate/api/gateway.api
GOFILES := $(shell find . -name '*.go')

.DEFAULT_GOAL := help

help: ## 顯示可用指令
	@echo "Haixun Backend"
	@echo ""
	@grep -E '^[a-zA-Z0-9_-]+:.*## ' $(MAKEFILE_LIST) | sort | awk 'BEGIN {FS = ":.*## "}; {printf "  make %-12s %s\n", $$1, $$2}'

tools: ## 安裝 goctl / goimports
	@command -v $(GOCTL) >/dev/null 2>&1 || (echo ">> installing goctl" && $(GO) install github.com/zeromicro/go-zero/tools/goctl@latest)
	@command -v goimports >/dev/null 2>&1 || (echo ">> installing goimports" && $(GO) install golang.org/x/tools/cmd/goimports@latest)

gen-api: tools ## 由 .api 生成 handler / logic / types
	$(GOCTL) api go -api $(API_ENTRY) -dir . -style $(GO_ZERO_STYLE) -home generate/goctl

fmt: ## gofmt + goimports
	$(GOFMT) -s -w $(GOFILES)
	@command -v goimports >/dev/null 2>&1 && goimports -w . || true

test: ## 執行測試
	$(GO) test ./...

run: ## 啟動 API
	$(GO) run ./gateway.go -f etc/gateway.yaml

CONFIG ?= etc/gateway.yaml
INIT_TENANT ?= default
INIT_EMAIL ?= admin@30cm.net
INIT_PASSWORD ?= Fafafa54088!

tool-init: ## 初始化 Mongo indexes、預設權限與 admin 帳號
	$(GO) run ./cmd/tool init -f $(CONFIG) -tenant $(INIT_TENANT) -email $(INIT_EMAIL) -password '$(INIT_PASSWORD)'

tool: ## 執行 cmd/tool（例：make tool ARGS="init -f etc/gateway.yaml"）
	$(GO) run ./cmd/tool $(ARGS)

web-install: ## 安裝前端依賴
	cd web && npm install

web-dev: web-install ## 啟動前端 dev server（proxy 到 :8890）
	cd web && npm run dev

web-build: web-install ## 建置前端靜態檔
	cd web && npm run build

check: fmt test ## 格式化並測試
