package apiserver

import (
	"github.com/pingcap-inc/pinsights/internal/apiserver/config"
	"github.com/pingcap-inc/pinsights/internal/apiserver/options"
	"github.com/pingcap-inc/pinsights/pkg/app"
	"github.com/pingcap-inc/pinsights/pkg/log"
)

const commandDesc = `The Pinsights API Server is the back-end service for Pinsights. It provides RESTful API for the frontend.`

func NewApp(bname string) *app.App {
	opts := options.NewOptions()
	application := app.NewApp("Pinsights API Server",
		bname,
		app.WithOptions(opts),
		app.WithDescription(commandDesc),
		app.WithDefaultValidArgs(),
		app.WithRunFunc(run(opts)),
	)
	return application
}

func run(opts *options.Options) app.RunFunc {
	return func(bname string) error {
		log.Init(opts.Log)
		defer log.Flush()

		cfg, err := config.CreateConfigFromOptions(opts)
		if err != nil {
			return err
		}

		return Run(cfg)
	}
}
