package currency_admin

import (
	"github.com/gofiber/fiber/v2"
	"go.uber.org/zap"
	"penahub.gitlab.yandexcloud.net/pena-services/customer/internal/errors"
	"penahub.gitlab.yandexcloud.net/pena-services/customer/internal/interface/controller/http"
	"penahub.gitlab.yandexcloud.net/pena-services/customer/internal/interface/repository"
	"penahub.gitlab.yandexcloud.net/pena-services/customer/internal/models"
)

type Deps struct {
	CurrencyRepo *repository.CurrencyRepository
	MiddleWare   *http.MiddleWare
	Logger       *zap.Logger
}

type CurrencyController struct {
	currencyRepo *repository.CurrencyRepository
	middleWare   *http.MiddleWare
	logger       *zap.Logger
}

func NewCurrencyController(deps Deps) *CurrencyController {
	return &CurrencyController{
		currencyRepo: deps.CurrencyRepo,
		middleWare:   deps.MiddleWare,
		logger:       deps.Logger,
	}
}

func (receiver *CurrencyController) Update(ctx *fiber.Ctx) error {
	var req struct {
		items []string
	}
	if err := ctx.BodyParser(&req); err != nil {
		return receiver.middleWare.Error(ctx, fiber.StatusBadRequest, "failed to bind currencies")
	}

	currencies := req.items

	currencyList, err := receiver.currencyRepo.ReplaceCurrencies(ctx.Context(), &models.CurrencyList{
		Name:       models.DefaultCurrencyListName,
		Currencies: currencies,
	})
	if err != nil && err.Type() != errors.ErrNotFound {
		return receiver.middleWare.ErrorOld(ctx, err)
	}

	if err != nil && err.Type() == errors.ErrNotFound {
		newCurrencyList, err := receiver.currencyRepo.Insert(ctx.Context(), &models.CurrencyList{
			Name:       models.DefaultCurrencyListName,
			Currencies: currencies,
		})
		if err != nil && err.Type() != errors.ErrNotFound {
			return receiver.middleWare.ErrorOld(ctx, err)
		}
		return ctx.Status(fiber.StatusOK).JSON(newCurrencyList.Currencies)
	}

	return ctx.Status(fiber.StatusOK).JSON(currencyList.Currencies)
}
