package restricted

import (
	"strconv"

	"git.ma-al.com/goc_daniel/b2b/app/config"
	"git.ma-al.com/goc_daniel/b2b/app/delivery/middleware"
	"git.ma-al.com/goc_daniel/b2b/app/delivery/middleware/perms"
	"git.ma-al.com/goc_daniel/b2b/app/model"
	"git.ma-al.com/goc_daniel/b2b/app/service/currencyService"
	"git.ma-al.com/goc_daniel/b2b/app/utils/i18n"
	"git.ma-al.com/goc_daniel/b2b/app/utils/nullable"
	"git.ma-al.com/goc_daniel/b2b/app/utils/response"
	"git.ma-al.com/goc_daniel/b2b/app/utils/responseErrors"

	"github.com/gofiber/fiber/v3"
)

type CurrencyHandler struct {
	CurrencyService *currencyService.CurrencyService
	config          *config.Config
}

func NewCurrencyHandler() *CurrencyHandler {
	currencyService := currencyService.New()
	return &CurrencyHandler{
		CurrencyService: currencyService,
		config:          config.Get(),
	}
}

func CurrencyHandlerRoutes(r fiber.Router) fiber.Router {
	handler := NewCurrencyHandler()

	r.Post("/currency-rate", middleware.Require(perms.CurrencyWrite), handler.PostCurrencyRate)
	r.Get("/currency-rate/:id", handler.GetCurrencyRate)
	return r
}

func (h *CurrencyHandler) PostCurrencyRate(c fiber.Ctx) error {
	var currencyRate model.CurrencyRate
	if err := c.Bind().Body(&currencyRate); err != nil {
		return c.Status(responseErrors.GetErrorStatus(responseErrors.ErrJSONBody)).
			JSON(response.Make(nullable.GetNil(""), 0, responseErrors.GetErrorCode(c, responseErrors.ErrJSONBody)))
	}

	err := h.CurrencyService.CreateCurrencyRate(&currencyRate)
	if err != nil {
		return c.Status(responseErrors.GetErrorStatus(err)).
			JSON(response.Make(nullable.GetNil(""), 0, responseErrors.GetErrorCode(c, err)))
	}

	return c.JSON(response.Make(nullable.GetNil(""), 1, i18n.T_(c, response.Message_OK)))
}

func (h *CurrencyHandler) GetCurrencyRate(c fiber.Ctx) error {
	idStr := c.Params("id")
	id, err := strconv.Atoi(idStr)
	if err != nil {
		return c.Status(responseErrors.GetErrorStatus(err)).JSON(response.Make(nullable.GetNil(""), 0, responseErrors.GetErrorCode(c, err)))

	}

	currency, err := h.CurrencyService.GetCurrency(uint(id))
	if err != nil {
		return c.Status(responseErrors.GetErrorStatus(err)).JSON(response.Make(nullable.GetNil(""), 0, responseErrors.GetErrorCode(c, err)))
	}

	return c.JSON(response.Make(currency, 0, i18n.T_(c, response.Message_OK)))
}
