package itcronjob

import (
	"github.com/pingcap-inc/data-ingestion-tools/internal/itcronjob/config"
	option "github.com/pingcap-inc/data-ingestion-tools/internal/itcronjob/option"
	"github.com/pingcap-inc/data-ingestion-tools/pkg/app"
	"github.com/pingcap-inc/data-ingestion-tools/pkg/log"
)

const commandDesc = `The PCHub API Server is the back-end service for PingCAP Cloud Hub. 
It provides RESTful API for the frontend.`

// NewApp contructs the app and return it.
func NewApp(bname string) *app.App {
	opts := option.NewOptions()
	application := app.NewApp("PCHub API Server",
		bname,
		app.WithOptions(opts),
		app.WithDescription(commandDesc),
		app.WithDefaultValidArgs(),
		app.WithRunFunc(run(opts)),
		app.WithLoggerInitFunc(loggerInit(opts)),
	)

	return application
}

func loggerInit(opts *option.Options) app.LoggerInitFunc {
	return func() {
		log.Init(opts.Log)
		defer log.Flush()
	}
}

func run(opts *option.Options) app.RunFunc {
	return func(bname string) error {
		cfg, err := config.CreateConfigFromOptions(opts)
		if err != nil {
			return err
		}

		return Run(cfg)
	}
}
