package main

import (
	"context"
	"fmt"
	"net/http"
	"os"
	"os/signal"
	"syscall"
	"time"

	"bsm/full/module/base/mgt/internal/config"
	"bsm/full/module/base/mgt/internal/impl"
	"bsm/full/module/base/mgt/internal/routers"
	"git.apinb.com/bsm-sdk/core/infra"
	"git.apinb.com/bsm-sdk/core/middleware"
	"git.apinb.com/bsm-sdk/core/printer"

	"github.com/gin-contrib/sessions"
	"github.com/gin-contrib/sessions/cookie"
	"github.com/gin-gonic/gin"
)

var (
	ServiceKey = "mgt"
)

func Run() {
	config.New(ServiceKey)
	impl.NewImpl()

	app := gin.Default()

	sessionKey := config.Spec.SecretKey + "-session"
	store := cookie.NewStore([]byte(sessionKey))
	app.Use(sessions.Sessions("mysession", store))

	middleware.Mode(app)
	app.Use(middleware.Cors())

	app.HEAD("/", infra.Health)
	routers.Register(ServiceKey, app)

	addr := fmt.Sprintf(":%s", config.Spec.Port)
	srv := &http.Server{Addr: addr, Handler: app}

	go func() {
		if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
			panic(err)
		}
	}()

	printer.Success("[BSM - %s] Server Started at %s", ServiceKey, addr)

	quit := make(chan os.Signal, 1)
	signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
	<-quit

	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
	defer cancel()
	if err := srv.Shutdown(ctx); err != nil {
		panic(err)
	}
}

func main() {
	Run()
}
