package external

import (
	"encoding/json"
	"errors"
	"fmt"
	"log/slog"
	"net/http"
	"time"

	"quantex.com/qfixdpl/src/app"
)

const QApixService = "QApix"

func (s *Manager) Users(out any) (err error) {
	auth, ok := s.config.External[QApixService]
	if !ok {
		err = errors.New("error getting auth data for qapix service at Users")

		slog.Error(err.Error())

		return err
	}

	options := RequestOptions{
		Method:        http.MethodGet,
		Path:          "/api/v1/auth/data/users",
		Body:          nil,
		Retries:       0,
		Timeout:       lTimeout * time.Second,
		CacheDuration: -1,
		Auth:          &auth,
	}

	response, err := s.sendRequestToExternal(options)
	if err != nil {
		err = fmt.Errorf("error making request to qapix server. error: %w", err)

		slog.Error(err.Error())

		return err
	}

	err = json.Unmarshal(response, out)
	if err != nil {
		err = fmt.Errorf("error making request to qapix server. error: %w", err)

		slog.Error(err.Error())

		return err
	}

	return nil
}

func (s *Manager) UserByID(userID string, out any) (err error) {
	path := "/api/v1/auth/data/user_by_id/" + userID

	auth, ok := s.config.External[QApixService]
	if !ok {
		err = errors.New("error getting auth data for qapix service at UserByEmail")

		slog.Error(err.Error())

		return err
	}

	options := RequestOptions{
		Method:        http.MethodGet,
		Path:          path,
		Body:          nil,
		Retries:       3,
		Timeout:       sTimeout * time.Second,
		CacheDuration: time.Second * 10,
		Auth:          &auth,
	}

	res, err := s.sendRequestToExternal(options)
	if err != nil {
		err = fmt.Errorf("error making user_by_id request to qapix server. error: %w", err)

		slog.Error(err.Error())

		return err
	}

	err = json.Unmarshal(res, out)
	if err != nil {
		err = fmt.Errorf("error unmarshalling user by id from qapix server. error: %w", err)

		slog.Error(err.Error())

		return err
	}

	return nil
}

func (s *Manager) UserByEmail(email string, out *app.User) (err error) {
	path := "/api/v1/auth/data/user_by_email"

	auth, ok := s.config.External[QApixService]
	if !ok {
		err = errors.New("error getting auth data for qapix service at UserByEmail")

		slog.Error(err.Error())

		return err
	}

	options := RequestOptions{
		Method:        http.MethodPost,
		Path:          path,
		Body:          map[string]string{"Email": email},
		Retries:       3,
		Timeout:       sTimeout * time.Second,
		CacheDuration: time.Second * 10,
		Auth:          &auth,
	}

	res, err := s.sendRequestToExternal(options)
	if err != nil {
		err = fmt.Errorf("error making user_by_email request to qapix server. error: %w", err)

		slog.Error(err.Error())

		return err
	}

	err = json.Unmarshal(res, out)
	if err != nil {
		err = fmt.Errorf("error unmarshalling user by email from qapix server. error: %w", err)

		slog.Error(err.Error())

		return err
	}

	return nil
}
