package router

import (
	"fmt"
	"gateway/common/db"
	. "gateway/common/gatecode"
	"github.com/gogf/gf/v2/net/ghttp"
	"github.com/gogf/gf/v2/util/gconv"
)

type Manager struct {
	routers map[string]Router
}

// InitRouterManager 初始化系统代理路由
func InitRouterManager() (*Manager, error) {
	res := db.GateWatMySql.Query("SELECT status,middleground_code,url,function_code,ischeck,ischeck_auth,ischeck_blacklist,timeout,remark FROM front_proxy")
	if res == nil || len(*res) == 0 {
		return nil, fmt.Errorf("未发现可用路由")
	}
	routerManager := &Manager{
		routers: make(map[string]Router),
	}
	for _, row := range *res {
		if url := gconv.String(row["url"]); url != "" {
			routerManager.routers[url] = Router{
				Status:     gconv.Int(row["status"]),
				PowerCheck: gconv.Int(row["ischeck"]),
				AuthCheck:  gconv.Int(row["ischeck_auth"]),
				BlackCheck: gconv.Int(row["ischeck_blacklist"]) == 1,
				FuncCode:   gconv.String(row["function_code"]),
				MiddleCode: gconv.String(row["middleground_code"]),
				ReqUrl:     url,
				TimeOut:    gconv.Int64(row["timeout"]),
				Remark:     gconv.String(row["remark"]),
			}
		}
	}
	return routerManager, nil
}

// GetRouterRule 获取路由规则
func (m *Manager) GetRouterRule(url string) (*Router, error) {
	// WillDo:后续需要增加正则匹配
	rule, exists := m.routers[url]
	if !exists {
		return nil, NewErrorWithCode(GATEWAY_ROUTER_NOTFIND, fmt.Sprintf("未找到请求地址%s,请检查是否注册到数据库\n", url))
	}
	if rule.Status != 1 {
		return nil, NewErrorWithCode(GATEWAY_ROUTER_UPHOLD, fmt.Sprintf("接口状态：%d\n", rule.Status))
	}
	return &rule, nil
}

// InfusionContext 注入通用结构体gContext
func (m *Manager) InfusionContext(r *ghttp.Request) (err error) {
	var router *Router
	var GCtx = &GContext{}
	router, err = m.GetRouterRule(r.RequestURI)
	if err != nil {
		r.SetCtxVar(GContextKey, GCtx)
		return
	}
	GCtx.RouterRule = router
	//获取session
	jySess, _ := InitJySessionContext(r)
	GCtx.UserId = jySess.UserId
	GCtx.SessData = jySess.Data
	r.SetCtxVar(GContextKey, GCtx)
	return
}
