package controller

import (
	"github.com/gofiber/fiber/v2"
	"github.com/google/uuid"
	"github.com/rs/zerolog"

	"web-qudo-be/app/module/hero_contents/request"
	"web-qudo-be/app/module/hero_contents/service"

	utilRes "web-qudo-be/utils/response"
	utilVal "web-qudo-be/utils/validator"
)

type heroContentsController struct {
	service service.HeroContentsService
	Log     zerolog.Logger
}

type HeroContentsController interface {
	Show(c *fiber.Ctx) error
	Save(c *fiber.Ctx) error
	Update(c *fiber.Ctx) error
	Delete(c *fiber.Ctx) error
}

func NewHeroContentController(service service.HeroContentsService, log zerolog.Logger) HeroContentsController {
	return &heroContentsController{
		service: service,
		Log:     log,
	}
}

func (_i *heroContentsController) Show(c *fiber.Ctx) error {
	_i.Log.Info().Msg("GET /hero-content")

	data, err := _i.service.Show()
	if err != nil {
		_i.Log.Error().Err(err).Msg("failed get hero content")
		return err
	}

	return utilRes.Resp(c, utilRes.Response{
		Success:  true,
		Messages: utilRes.Messages{"Hero content retrieved"},
		Data:     data,
	})
}
func (_i *heroContentsController) Save(c *fiber.Ctx) error {
	req := new(request.HeroContentsCreateRequest)

	if err := utilVal.ParseAndValidate(c, req); err != nil {
		return err
	}

	data := req.ToEntity()

	result, err := _i.service.Save(data)
	if err != nil {
		_i.Log.Error().Err(err).Msg("failed create hero content")
		return err
	}

	return utilRes.Resp(c, utilRes.Response{
		Success:  true,
		Messages: utilRes.Messages{"Hero content created"},
		Data:     result,
	})
}

func (_i *heroContentsController) Update(c *fiber.Ctx) error {
	idStr := c.Params("id")

	id, err := uuid.Parse(idStr)
	if err != nil {
		return err
	}

	req := new(request.HeroContentsUpdateRequest)
	if err := utilVal.ParseAndValidate(c, req); err != nil {
		return err
	}

	err = _i.service.Update(id, req.ToEntity())
	if err != nil {
		_i.Log.Error().Err(err).Msg("failed update hero content")
		return err
	}

	return utilRes.Resp(c, utilRes.Response{
		Success:  true,
		Messages: utilRes.Messages{"Hero content updated"},
	})
}

func (_i *heroContentsController) Delete(c *fiber.Ctx) error {
	idStr := c.Params("id")

	id, err := uuid.Parse(idStr)
	if err != nil {
		return err
	}

	err = _i.service.Delete(id)
	if err != nil {
		_i.Log.Error().Err(err).Msg("failed delete hero content")
		return err
	}

	return utilRes.Resp(c, utilRes.Response{
		Success:  true,
		Messages: utilRes.Messages{"Hero content deleted"},
	})
}