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/helper/request"
	"git.dmitriygnatenko.ru/dima/dmitriygnatenko-v2/internal/service/handler"
	"git.dmitriygnatenko.ru/dima/dmitriygnatenko-v2/internal/service/i18n"
)

type deleteTagPage struct {
	tagRepository      TagRepository
	languageRepository LanguageRepository
	cacheService       CacheService
}

func NewDeleteTagPageHandler(
	tagRepository TagRepository,
	languageRepository LanguageRepository,
	cacheService CacheService,
) fiber.Handler {
	h := deleteTagPage{
		tagRepository:      tagRepository,
		languageRepository: languageRepository,
		cacheService:       cacheService,
	}

	return h.handler()
}

func (h deleteTagPage) handler() fiber.Handler {
	return func(fctx *fiber.Ctx) error {
		ctx := fctx.Context()
		lang := i18n.LanguageFromContext(fctx)

		id, err := request.ConvertToUint64(fctx, "id")
		if err != nil {
			logger.Error(ctx, customErrors.Wrap(err, "delete tag page: can't get id from request").Error())
			return err
		}

		tag, err := h.tagRepository.GetByID(ctx, id)
		if err != nil {
			logger.Error(ctx, customErrors.Wrap(err, "delete tag page: can't get tag").Error())
			return err
		}

		used, err := h.tagRepository.IsUsed(ctx, id)
		if err != nil {
			logger.Error(ctx, customErrors.Wrap(err, "delete tag page: can't check is used").Error())
			return err
		}

		if fctx.Method() == fiber.MethodPost {
			err = h.tagRepository.Delete(ctx, id)
			if err != nil {
				logger.Error(ctx, customErrors.Wrap(err, "delete tag page: can't delete tag").Error())
				return err
			}

			languages, err := h.languageRepository.GetAll(ctx)
			if err != nil {
				logger.Error(ctx, customErrors.Wrap(err, "edit tag page: can't get languages").Error())
				return err
			}

			for i := range languages {
				h.cacheService.Delete(handler.TagCacheKey + languages[i].URL + tag.URL)
				h.cacheService.Delete(handler.UsedTagsCacheKey + languages[i].URL)
			}

			return fctx.Redirect("/admin/tag")
		}

		return fctx.Render("admin/tag_delete", fiber.Map{
			"lang":    lang,
			"section": "tag",
			"used":    used,
			"tag":     tag.Tag,
		}, "admin/_layout")
	}
}
