package admin

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

	customErrors "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"
)

type articleListPage struct {
	articleRepository ArticleRepository
}

func NewArticleListPageHandler(
	articleRepository ArticleRepository,
) fiber.Handler {
	h := articleListPage{
		articleRepository: articleRepository,
	}

	return h.handler()
}

func (h articleListPage) handler() fiber.Handler {
	return func(ctx *fiber.Ctx) error {
		lang := i18n.LanguageFromContext(ctx)
		articles, err := h.articleRepository.GetAll(ctx.Context())
		if err != nil {
			logger.Error(ctx.Context(), customErrors.Wrap(err, "articles list page: can't get articles").Error())
			return err
		}

		return ctx.Render("admin/article", fiber.Map{
			"section":  "article",
			"lang":     lang,
			"articles": mapper.ToArticlesList(lang, articles),
		}, "admin/_layout")
	}
}
