package handler

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

	"git.dmitriygnatenko.ru/dima/dmitriygnatenko-v2/internal/helper/errors"
	"git.dmitriygnatenko.ru/dima/dmitriygnatenko-v2/internal/mapper"
	"git.dmitriygnatenko.ru/dima/dmitriygnatenko-v2/internal/service/i18n"
)

const AllPreviewArticlesCacheKey = "all-preview-articles"

type mainPage struct {
	cacheService      CacheService
	articleRepository ArticleRepository
}

func NewMainPageHandler(
	cacheService CacheService,
	articleRepository ArticleRepository,
) fiber.Handler {
	h := mainPage{
		cacheService:      cacheService,
		articleRepository: articleRepository,
	}

	return h.handler()
}

func (h *mainPage) handler() fiber.Handler {
	return func(fctx *fiber.Ctx) error {
		ctx := fctx.Context()
		lang := i18n.LanguageFromContext(fctx)
		cacheKey := AllPreviewArticlesCacheKey + string(lang)

		renderData, found := h.cacheService.Get(cacheKey)
		if !found {
			articleModels, err := h.articleRepository.GetAllPreview(ctx, i18n.LanguageID(lang))
			if err != nil {
				logger.Error(ctx, errors.Wrap(err, "main page: can't get articles").Error())
				return err
			}

			renderData = fiber.Map{
				"lang":            lang,
				"headTitle":       i18n.T(lang, "head_title"),
				"pageTitle":       i18n.T(lang, "main_page_title"),
				"headDescription": i18n.T(lang, "main_page_desc"),
				"headKeywords":    i18n.T(lang, "main_page_keywords"),
				"articles":        mapper.ToArticlesPreview(lang, articleModels),
			}

			h.cacheService.Set(cacheKey, renderData, nil)
		}

		return fctx.Render("index", renderData, "_layout")
	}
}
