package main

import (
	"flag"
	"github.com/zeromicro/go-zero/core/logx"
	"gitlab.fjmaimaimai.com/allied-creation/sumifcc-bchart/cmd/chart-server/interanl/pkg/db"
	"gitlab.fjmaimaimai.com/allied-creation/sumifcc-bchart/cmd/chart-server/interanl/pkg/domain"
	"net/http"
	"strings"

	"github.com/golang-jwt/jwt/v4/request"

	"gitlab.fjmaimaimai.com/allied-creation/sumifcc-bchart/cmd/chart-server/api/internal/config"
	"gitlab.fjmaimaimai.com/allied-creation/sumifcc-bchart/cmd/chart-server/api/internal/handler"
	"gitlab.fjmaimaimai.com/allied-creation/sumifcc-bchart/cmd/chart-server/api/internal/svc"

	"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)

	// 默认的token头 Authorization 修改未 x-token
	request.AuthorizationHeaderExtractor = &request.PostExtractionFilter{
		request.HeaderExtractor{"x-mmm-accesstoken"}, func(tok string) (string, error) {
			// Should be a bearer token
			if len(tok) > 6 && strings.ToUpper(tok[0:7]) == "BEARER " {
				return tok[7:], nil
			}
			return tok, nil
		},
	}

	// 初始化Domain里面的配置
	domain.ProjectName = c.Name

	opts := make([]rest.RunOption, 0)
	// cors
	opt := rest.WithCustomCors(func(header http.Header) {
		header.Set("Access-Control-Allow-Headers", "*")
	}, func(writer http.ResponseWriter) {

	})
	opts = append(opts, opt)

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

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

	db.Migrate(ctx.DB)

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