package example

import (
	"fmt"
	"log/slog"

	"quantex.com/qfixdpl/src/app"
	googlechat "quantex.com/qfixdpl/src/client/notify/google"
	"quantex.com/qfixdpl/src/client/store/external"
	"quantex.com/qfixdpl/src/common/tracerr"
	"quantex.com/qfixdpl/src/domain"
)

func ExternalRunner(cfg app.Config) error {
	notify := googlechat.New(cfg.Notify.Google)

	slog.Info("Hello Try API")

	return tryExternal(notify, cfg)
}

func tryExternal(notify *googlechat.Notify, cfg app.Config) error {
	fmt.Println("\n @@@@@@@@@ Try External @@@@@@@@@ ")
	defer fmt.Println("\n @@@@@@@@@ End Try External @@@@@@@@@ ")

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

	ext := external.NewManager(notify, extConfig)

	var users []app.User

	err := ext.Users(&users)
	if err != nil {
		return tracerr.Errorf("unable to read users: %w", err)
	}

	slog.Info("Users count", "count", len(users))

	if len(users) == 0 {
		return tracerr.Errorf("error, users list is empty!")
	}

	user := users[len(users)/2]

	var user1 domain.User

	err = ext.UserByID(user.UserID, &user1)
	if err != nil {
		return tracerr.Errorf("error UserByID %w", err)
	}

	slog.Info(fmt.Sprintf("UserByID: %+v", user1))

	var user2 app.User

	err = ext.UserByEmail(user.Email, &user2)
	if err != nil {
		return tracerr.Errorf("error UserByEmail %+v\n", err)
	}

	slog.Info(fmt.Sprintf("UserByEmail: %+v", user2))

	var badType []app.UserDataProvider

	err = ext.Users(&badType)
	if err == nil {
		return tracerr.Errorf("error users count: %v", len(badType))
	}

	slog.Info("Correct wrong type " + err.Error())

	return nil
}
