package main

import (
	"flag"
	"fmt"
	"net/http"

	"git.i2edu.net/i2/i2-bill-api/internal/config"
	"git.i2edu.net/i2/i2-bill-api/internal/handler"
	"git.i2edu.net/i2/i2-bill-api/internal/svc"
	"git.i2edu.net/i2/i2-bill-api/internal/utils"

	"git.i2edu.net/i2/go-zero/core/conf"
	"git.i2edu.net/i2/go-zero/rest"
	"git.i2edu.net/i2/go-zero/rest/httpx"
)

var configFile = flag.String("f", "etc/i2bill-api.yaml", "the config file")
var withUnauthorizedCallback = rest.WithUnauthorizedCallback(func(w http.ResponseWriter, r *http.Request, err error) {
	httpx.OkJson(w, utils.ReturnHTTPUnauthorized(err))
})

func main() {
	flag.Parse()

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

	ctx := svc.NewServiceContext(c)
	server := rest.MustNewServer(c.RestConf, withUnauthorizedCallback)
	defer server.Stop()

	handler.RegisterHandlers(server, ctx)

	server.Use(handler.Cors(ctx))
	server.AddRoutes(handler.CorsCheck())

	server.AddRoutes(handler.Static("/asserts/", handler.LocalFile("asserts", false)))
	fmt.Printf("Starting server at %s:%d...\n", c.Host, c.Port)
	server.Start()
}
