package main

import (
	"flag"
	"fmt"

	"sundynix-micro-go/app/system/rpc/systemservice"
	"sundynix-micro-go/app/zero-gateway/internal/config"
	"sundynix-micro-go/app/zero-gateway/internal/middleware"

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

var configFile = flag.String("f", "etc/zero-gateway.yaml", "the config file")

func main() {
	flag.Parse()
	stat.DisableLog()

	var c config.Config
	conf.MustLoad(*configFile, &c)

	// 初始化 system-rpc 客户端（用于异步写入操作日志）
	systemRpc := systemservice.NewSystemService(zrpc.MustNewClient(c.SystemRpc))

	// 构建各中间件实例
	corsMiddleware := middleware.NewCorsMiddleware(
		c.Cors.AllowOrigins,
		c.Cors.AllowMethods,
		c.Cors.AllowHeaders,
	)
	authMiddleware := middleware.NewAuthMiddleware(c.JwtSecret, c.AuthWhitelist)
	opLogMiddleware := middleware.NewOperationLogMiddleware(systemRpc, c.JwtSecret)

	// 构建官方 Gateway，注入中间件（执行顺序：CORS → Auth → OpLog → 上游转发）
	gw := gateway.MustNewServer(c.GatewayConf,
		gateway.WithMiddleware(
			rest.Middleware(corsMiddleware.Handle),  // 跨域
			rest.Middleware(authMiddleware.Handle),  // JWT 鉴权
			rest.Middleware(opLogMiddleware.Handle), // 操作日志（异步写入 system-rpc）
		),
	)
	defer gw.Stop()

	fmt.Println("===== Sundynix Zero-Gateway (Official) =====")
	logx.Infof("监听地址: %s:%d", c.Host, c.Port)
	logx.Infof("上游服务: %d 个", len(c.Upstreams))
	logx.Infof("中间件: CORS | JWT鉴权 | 操作日志→system-rpc")
	logx.Infof("鉴权白名单: %d 条", len(c.AuthWhitelist))
	for _, u := range c.Upstreams {
		if u.Http.Target != "" {
			logx.Infof("  [HTTP] %-15s -> %s (prefix: %s, routes: %d)",
				u.Name, u.Http.Target, u.Http.Prefix, len(u.Mappings))
		}
		if u.Grpc.Target != "" {
			logx.Infof("  [gRPC] %-15s -> %s (routes: %d)",
				u.Name, u.Grpc.Target, len(u.Mappings))
		}
	}
	fmt.Println("=============================================")

	gw.Start()
}
