package main

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

	"aijianzhan/platform/internal/config"
	"aijianzhan/platform/internal/handler"
	"aijianzhan/platform/internal/license"
	"aijianzhan/platform/internal/svc"

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

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

func main() {
	flag.Parse()

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

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

	ctx := svc.NewServiceContext(c)
	server.Use(func(next http.HandlerFunc) http.HandlerFunc {
		return license.Middleware(ctx.License)(next)
	})
	handler.RegisterHandlers(server, ctx)

	runCtx, cancel := context.WithCancel(context.Background())
	defer cancel()
	if ctx.DBSync != nil {
		ctx.DBSync.StartAll(runCtx)
	}

	go func() {
		ch := make(chan os.Signal, 1)
		signal.Notify(ch, syscall.SIGINT, syscall.SIGTERM)
		<-ch
		cancel()
		server.Stop()
	}()

	fmt.Printf("platform starting at %s:%d (memoryMode=%v dryRun=%v dbsync=%v)\n",
		c.Host, c.Port, ctx.MemoryMode, c.DryRun, ctx.DBSync != nil)
	server.Start()
}
