package currency

import (
	"fmt"
	"log"
	"net/http"

	"github.com/labstack/echo/v4"
	"go.uber.org/zap"
	"penahub.gitlab.yandexcloud.net/pena-services/customer/internal/errors"
	"penahub.gitlab.yandexcloud.net/pena-services/customer/internal/service/currency"
	"penahub.gitlab.yandexcloud.net/pena-services/customer/pkg/echotools"
)

type Deps struct {
	Logger          *zap.Logger
	CurrencyService *currency.Service
}

type Controller struct {
	logger          *zap.Logger
	currencyService *currency.Service
}

func New(deps Deps) *Controller {
	if deps.Logger == nil {
		log.Panicln("logger is nil on <New (account controller)>")
	}

	if deps.CurrencyService == nil {
		log.Panicln("currency service is nil on <New (account controller)>")
	}

	return &Controller{
		logger:          deps.Logger,
		currencyService: deps.CurrencyService,
	}
}

func (receiver *Controller) GetCurrencies(ctx echo.Context) error {
	currencies, err := receiver.currencyService.GetCurrencies(ctx.Request().Context())
	if err != nil {
		receiver.logger.Error(
			"failed to get currencies on <GetCurrencies> of <CurrencyController>",
			zap.Error(err),
		)
		return errors.HTTP(ctx, err)
	}

	return ctx.JSON(http.StatusOK, currencies)
}

func (receiver *Controller) PutCurrencies(ctx echo.Context) error {
	currencies, bindErr := echotools.Bind[[]string](ctx)
	if bindErr != nil {
		receiver.logger.Error(
			"failed to parse body on <PutCurrencies> of <CurrencyController>",
			zap.Error(bindErr),
		)
		return errors.HTTP(ctx, errors.New(
			fmt.Errorf("failed to parse body: %w", bindErr),
			errors.ErrInvalidArgs,
		))
	}

	currenciesCopy := *currencies

	if len(currenciesCopy) < 1 {
		currenciesCopy = make([]string, 0)
	}

	updatedCurrencies, err := receiver.currencyService.PutCurrencies(ctx.Request().Context(), currenciesCopy)
	if err != nil {
		receiver.logger.Error(
			"failed to put currencies on <PutCurrencies> of <CurrencyController>",
			zap.Error(err),
		)
		return errors.HTTP(ctx, err)
	}

	return ctx.JSON(http.StatusOK, updatedCurrencies)
}
