// Package service contain the main service runner
package service

import (
	"fmt"
	"log/slog"

	"quantex.com/qfixdpl/src/app"
	"quantex.com/qfixdpl/src/client/api/rest"
	"quantex.com/qfixdpl/src/client/data"
	"quantex.com/qfixdpl/src/client/fix"
	googlechat "quantex.com/qfixdpl/src/client/notify/google"
	"quantex.com/qfixdpl/src/client/store"
	"quantex.com/qfixdpl/src/client/store/external"
	"quantex.com/qfixdpl/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()

	fixManager := fix.NewManager(cfg.FIX, appStore, notify)
	if err = fixManager.Start(); err != nil {
		return fmt.Errorf("error starting FIX acceptor: %w", err)
	}
	defer fixManager.Stop()

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

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

	cmd.WaitForInterruptSignal(nil)

	return nil
}
