package fiber

import (
	"errors"

	"git.dmitriygnatenko.ru/dima/go-common/logger"
	"github.com/gofiber/fiber/v2"
	"github.com/gofiber/template/html/v2"

	customErrors "git.dmitriygnatenko.ru/dima/dmitriygnatenko-v2/internal/helper/errors"
	"git.dmitriygnatenko.ru/dima/dmitriygnatenko-v2/internal/service/i18n"
	"git.dmitriygnatenko.ru/dima/dmitriygnatenko-v2/internal/template/functions"
)

func getViewsEngine(sp ServiceProvider) *html.Engine {
	engine := html.New(sp.ConfigService().AppTemplatesPath(), ".html")

	engine.AddFunc("now", functions.Now)
	engine.AddFunc("noescape", functions.NoEscape)
	engine.AddFunc("concat", functions.Concat)
	engine.AddFunc("gridsep", functions.GridSep)
	engine.AddFunc("version", functions.Version(sp))
	engine.AddFunc("trans", functions.Trans)
	engine.AddFunc("link", functions.Link)

	return engine
}

func getErrorHandler() fiber.ErrorHandler {
	return func(fctx *fiber.Ctx, err error) error {
		lang := i18n.LanguageFromContext(fctx)
		errCode := fiber.StatusInternalServerError
		var e *fiber.Error
		if errors.As(err, &e) {
			errCode = e.Code
		}

		renderData := fiber.Map{
			"lang":      lang,
			"headTitle": i18n.T(lang, "head_title"),
		}

		if errCode == fiber.StatusNotFound {
			renderData["pageTitle"] = i18n.T(lang, "page_not_found_err_title")
			renderData["code"] = fiber.StatusNotFound
			renderData["text"] = i18n.T(lang, "page_not_found_err_desc")
		} else {
			renderData["pageTitle"] = i18n.T(lang, "internal_err_title")
			renderData["code"] = fiber.StatusInternalServerError
			renderData["text"] = i18n.T(lang, "internal_err_desc")
		}

		if err = fctx.Render("error", renderData, "_layout"); err != nil {
			logger.Error(fctx.Context(), customErrors.Wrap(err, "render error template").Error())
		}

		return nil
	}
}
