// Package service contain the main service runner
package service

import (
	"fmt"
	"log/slog"

	"quantex.com/qfixpt/src/app"
	"quantex.com/qfixpt/src/client/api/rest"
	"quantex.com/qfixpt/src/client/data"
	"quantex.com/qfixpt/src/client/fix"
	googlechat "quantex.com/qfixpt/src/client/notify/google"
	"quantex.com/qfixpt/src/client/store"
	"quantex.com/qfixpt/src/client/store/external"
	"quantex.com/qfixpt/src/cmd"
)

func Runner(cfg app.Config) error {
	slog.Info("Hello Try Service")

	notify := googlechat.New(cfg.Notify.Google)

	extConfig := external.Config{
		QApixPort:  cfg.APIBasePort,
		QApixHost:  cfg.QApixHost,
		External:   cfg.External,
		QApixToken: cfg.QApixToken,
	}

	storeConfig := store.Config{
		MultiDB:  cfg.MultiDB,
		External: extConfig,
	}

	appStore, err := store.New(storeConfig)
	if err != nil {
		return fmt.Errorf("error trying to create store %w", err)
	}

	userData := data.New()

	// Initialize FIX Post-Trade Manager.
	fixManager := fix.NewManager(cfg.FIX, appStore, notify)
	if err = fixManager.Start(); err != nil {
		return fmt.Errorf("error starting FIX initiator: %w", err)
	}
	defer fixManager.Stop()

	apiConfig := rest.Config{
		Port:               cfg.APIBasePort,
		AllowedOrigins:     cfg.AllowedOrigins,
		External:           cfg.External,
		AuthorizedServices: cfg.AuthorizedServices,
		EnableJWTAuth:      cfg.EnableJWTAuth,
	}

	api := rest.New(userData, appStore, fixManager, apiConfig, notify)
	api.Run()

	cmd.WaitForInterruptSignal(nil)

	return nil
}
