package controller

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

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

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

type ourProductContentController struct {
	service service.OurProductContentService
	Log     zerolog.Logger
}

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

func NewOurProductContentController(service service.OurProductContentService, log zerolog.Logger) OurProductContentController {
	return &ourProductContentController{
		service: service,
		Log:     log,
	}
}

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

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

	return utilRes.Resp(c, utilRes.Response{
		Success:  true,
		Messages: utilRes.Messages{"Our product content retrieved"},
		Data:     data,
	})
}

func (_i *ourProductContentController) Save(c *fiber.Ctx) error {
	req := new(request.OurProductContentCreateRequest)

	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 our product content")
		return err
	}

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

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

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

	req := new(request.OurProductContentUpdateRequest)
	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 our product content")
		return err
	}

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

func (_i *ourProductContentController) 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 our product content")
		return err
	}

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