package client

import (
	"context"
	"fmt"
	"log"
	"strconv"

	"gitea.pena/PenaSide/customer/internal/errors"
	"gitea.pena/PenaSide/customer/internal/models"
	"gitea.pena/PenaSide/customer/internal/utils"
	"gitea.pena/PenaSide/customer/pkg/client"
	"go.uber.org/zap"
)

type CurrencyClientDeps struct {
	Logger *zap.Logger
	URL    string
}

type CurrencyClient struct {
	logger *zap.Logger
	url    string
}

func NewCurrencyClient(deps CurrencyClientDeps) *CurrencyClient {
	if deps.Logger == nil {
		log.Panicln("logger is nil on <NewCurrencyClient>")
	}

	if deps.URL == "" {
		log.Panicln("urls is nil on <NewCurrencyClient>")
	}

	return &CurrencyClient{
		logger: deps.Logger,
		url:    deps.URL,
	}
}

func (receiver *CurrencyClient) Translate(ctx context.Context, request *models.TranslateCurrency) (int64, errors.Error) {
	response, err := client.Get[models.CurrencyClientResponse[int64], models.CurrencyClientResponse[string]](ctx, &client.RequestSettings{
		URL:     fmt.Sprintf("%s/change", receiver.url),
		Headers: map[string]string{"Content-Type": "application/json"},
		QueryParams: map[string]string{
			"currencyFrom": request.From,
			"currencyTo":   request.To,
			"value":        strconv.FormatInt(request.Money, 10),
		},
	})
	if err != nil {
		receiver.logger.Error("failed to request on <Translate> of <CurrencyClient>",
			zap.Error(err),
			zap.String("from", request.From),
			zap.String("to", request.To),
			zap.Int64("money", request.Money),
		)

		return 0, errors.New(
			fmt.Errorf("failed to request on <Translate> of <CurrencyClient>: %w", err),
			errors.ErrInternalError,
		)
	}
	if response.Error != nil {
		receiver.logger.Error("failed translate currency on <Translate> of <CurrencyClient>",
			zap.String("error", response.Error.Message),
			zap.String("from", request.From),
			zap.String("to", request.To),
			zap.Int64("money", request.Money),
		)

		return 0, errors.New(
			fmt.Errorf("failed translate currency on <Translate> of <CurrencyClient>: %s", response.Error.Message),
			utils.DetermineClientErrorResponse(response.StatusCode),
		)
	}

	return response.Body.Message, nil
}
