package controller

import (
	"strconv"

	"github.com/gofiber/fiber/v2"
	"github.com/rs/zerolog"

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

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

type ourServiceContentController struct {
	service service.OurServiceContentService
	Log     zerolog.Logger
}

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

func NewOurServiceContentController(service service.OurServiceContentService, log zerolog.Logger) OurServiceContentController {
	return &ourServiceContentController{
		service: service,
		Log:     log,
	}
}

func (_i *ourServiceContentController) Show(c *fiber.Ctx) error {
	_i.Log.Info().Msg("GET /our-service-contents")

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

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

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

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

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

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

	id, err := strconv.Atoi(idStr)
	if err != nil {
		return err
	}

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

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

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

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

	id, err := strconv.Atoi(idStr)
	if err != nil {
		return err
	}

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

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