package main

import (
	"context"
	"flag"
	"fmt"
	"os"
	"time"

	"apps/backend/internal/config"
	"apps/backend/internal/handler"
	"apps/backend/internal/lib/securelog"
	"apps/backend/internal/middleware"
	"apps/backend/internal/svc"

	"github.com/zeromicro/go-zero/core/conf"
	"github.com/zeromicro/go-zero/core/logx"
	"github.com/zeromicro/go-zero/rest"
)

// Gateway entry (go-zero). API from goctl; DB schema from generate/database migrate.
func main() {
	// 必須在 mon/monc 建立前呼叫：否則 Mongo ReplaceOne 會把 password_hash 整包打進 log
	securelog.SilenceMongo()

	configFile := flag.String("f", "etc/gateway.yaml", "config file")
	flag.Parse()

	var c config.Config
	conf.MustLoad(*configFile, &c)
	c.ApplyEnv()
	if err := c.ValidateProductionDependencies(); err != nil {
		logx.Must(err)
	}

	// 禁止 Verbose（否則可能印 request body 含 password）
	c.RestConf.Verbose = false

	server := rest.MustNewServer(c.RestConf,
		rest.WithNotAllowedHandler(middleware.NewCorsMiddleware(c.CORSAllowedOrigins).Handler()),
	)
	defer server.Stop()
	server.Use(middleware.NewCorsMiddleware(c.CORSAllowedOrigins).Handle)

	ctx := svc.NewServiceContext(c)
	pingCtx, cancelPing := context.WithTimeout(context.Background(), 3*time.Second)
	redisReady := ctx.Redis != nil && ctx.Redis.PingCtx(pingCtx)
	cancelPing()
	if !redisReady {
		logx.Must(fmt.Errorf("redis startup ping failed"))
	}
	handler.RegisterHandlers(server, ctx)
	// 靈感 SSE stream（goctl 不生成 streaming handler）
	handler.RegisterInspireStream(server, ctx)

	logx.Infof("haixun gateway %s:%d pid=%d", c.Host, c.Port, os.Getpid())
	fmt.Printf("Starting server at %s:%d...\n", c.Host, c.Port)
	server.Start()
}
