package main

import (
	"flag"
	"fmt"
	"github.com/zeromicro/go-zero/core/logx"
	"github.com/zeromicro/go-zero/rest/httpx"
	"gitlab.fjmaimaimai.com/allied-creation/su-micro/cmd/ep/system/api/internal/config"
	"gitlab.fjmaimaimai.com/allied-creation/su-micro/cmd/ep/system/api/internal/handler"
	"gitlab.fjmaimaimai.com/allied-creation/su-micro/cmd/ep/system/api/internal/svc"
	"gitlab.fjmaimaimai.com/allied-creation/su-micro/cmd/ep/system/internal/pkg/db"
	"gitlab.fjmaimaimai.com/allied-creation/su-micro/cmd/ep/system/internal/pkg/domain"
	"gitlab.fjmaimaimai.com/allied-creation/su-micro/pkg/gateway/smslib"
	"gitlab.fjmaimaimai.com/allied-creation/su-micro/pkg/tool"
	"gitlab.fjmaimaimai.com/allied-creation/su-micro/pkg/xerr"
	"net/http"

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

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

func main() {
	flag.Parse()

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

	// 系统设置
	systemSetup(c)

	// 服务初始化
	opts := make([]rest.RunOption, 0)
	opts = append(opts, rest.WithCustomCors(func(header http.Header) {
		header.Set("Access-Control-Allow-Headers", "*")
	}, func(writer http.ResponseWriter) {

	}))
	opts = append(opts, rest.WithUnauthorizedCallback(func(w http.ResponseWriter, r *http.Request, err error) {
		if err != nil {
			logx.Debugf("unauthorized: %s \n", err.Error())
		}
		httpx.WriteJson(w, http.StatusUnauthorized, xerr.Error(xerr.TokenExpireError, err.Error()))
		return
	}))

	server := rest.MustNewServer(c.RestConf, opts...)
	defer server.Stop()

	ctx := svc.NewServiceContext(c)
	handler.RegisterHandlers(server, ctx)
	server.AddRoutes(RoutersOpenapi(ctx))

	// 数据迁移
	if c.Migrate {
		db.Migrate(ctx.DB)
	}

	fmt.Printf("Starting server at %s:%d...\n", c.Host, c.Port)
	server.Start()
}

func systemSetup(c config.Config) {
	// 初始化Domain里面的配置
	domain.ProjectName = c.Name

	// 系统错误应答包装
	httpx.SetErrorHandlerCtx(xerr.ErrorHandlerCtx)

	// 系统成功应答包装
	httpx.SetOkHandler(xerr.OkHandlerCtx)
}

func RoutersOpenapi(svc *svc.ServiceContext) []rest.Route {
	return []rest.Route{
		{
			Method:  http.MethodPost,
			Path:    "/v1/openapi/sms/send-sms-code",
			Handler: smslib.SendSmsCodeHandler(svc.SmsService),
		},
		{
			Method:  http.MethodGet,
			Path:    "/log/:module",
			Handler: tool.LogHandler(svc.Config.Log),
		},
		{
			Method:  http.MethodGet,
			Path:    "/cache/clear/:app",
			Handler: tool.ClearCacheHandler(svc.Redis),
		},
	}
}