package controller

import (
	"web-qudo-be/app/module/clients/request"
	"web-qudo-be/app/module/clients/service"
	"web-qudo-be/utils/paginator"

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

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

type clientsController struct {
	clientsService service.ClientsService
	Log            zerolog.Logger
}

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

func NewClientsController(clientsService service.ClientsService, log zerolog.Logger) ClientsController {
	return &clientsController{
		clientsService: clientsService,
		Log:            log,
	}
}

// All get all Clients
// @Summary      Get all Clients
// @Description  API for getting all Clients
// @Tags         Clients
// @Security     Bearer
// @Param 	     req query request.ClientsQueryRequest false "query parameters"
// @Param 	     req query paginator.Pagination false "pagination parameters"
// @Success      200  {object}  response.Response
// @Failure      400  {object}  response.BadRequestError
// @Failure      401  {object}  response.UnauthorizedError
// @Failure      500  {object}  response.InternalServerError
// @Router       /clients [get]
func (_i *clientsController) All(c *fiber.Ctx) error {

	_i.Log.Info().Msg("GET /clients endpoint hit")

	paginate, err := paginator.Paginate(c)
	if err != nil {
		_i.Log.Error().Err(err).Msg("Pagination error")
		return err
	}

	reqContext := request.ClientsQueryRequestContext{
		Name:        c.Query("name"),
		CreatedById: c.Query("createdById"),
	}

	_i.Log.Info().
		Str("name", reqContext.Name).
		Str("createdById", reqContext.CreatedById).
		Msg("Query params received")

	req := reqContext.ToParamRequest()
	req.Pagination = paginate

	_i.Log.Info().Interface("request", req).Msg("Request after conversion")

	clientsData, paging, err := _i.clientsService.All(req)
	if err != nil {
		_i.Log.Error().Err(err).Msg("Service error while getting clients")
		return err
	}

	_i.Log.Info().
		Int("data_count", len(clientsData)).
		Msg("Clients successfully retrieved")

	return utilRes.Resp(c, utilRes.Response{
		Success:  true,
		Messages: utilRes.Messages{"Clients list successfully retrieved"},
		Data:     clientsData,
		Meta:     paging,
	})
}

// Show get one Clients
// @Summary      Get one Clients
// @Description  API for getting one Clients
// @Tags         Clients
// @Security     Bearer
// @Param        id path int true "Clients ID"
// @Success      200  {object}  response.Response
// @Failure      400  {object}  response.BadRequestError
// @Failure      401  {object}  response.UnauthorizedError
// @Failure      500  {object}  response.InternalServerError
// @Router       /clients/{id} [get]
func (_i *clientsController) Show(c *fiber.Ctx) error {
	idStr := c.Params("id")
	id, err := uuid.Parse(idStr)
	if err != nil {
		return err
	}

	clientsData, err := _i.clientsService.Show(id)
	if err != nil {
		return err
	}

	return utilRes.Resp(c, utilRes.Response{
		Success:  true,
		Messages: utilRes.Messages{"Clients successfully retrieved"},
		Data:     clientsData,
	})
}

// Save create Clients
// @Summary      Create Clients
// @Description  API for create Clients
// @Tags         Clients
// @Security     Bearer
// @Param        Authorization header string false "Insert your access token" default(Bearer <Add access token here>)
// @Param 	     payload body request.ClientsCreateRequest true "Required payload"
// @Success      200  {object}  response.Response
// @Failure      400  {object}  response.BadRequestError
// @Failure      401  {object}  response.UnauthorizedError
// @Failure      500  {object}  response.InternalServerError
// @Router       /clients [post]
func (_i *clientsController) Save(c *fiber.Ctx) error {
	req := new(request.ClientsCreateRequest)
	if err := utilVal.ParseAndValidate(c, req); err != nil {
		return err
	}

	authToken := c.Get("Authorization")
	dataResult, err := _i.clientsService.Save(*req, authToken)
	if err != nil {
		return err
	}

	return utilRes.Resp(c, utilRes.Response{
		Success:  true,
		Messages: utilRes.Messages{"Clients successfully created"},
		Data:     dataResult,
	})
}

// Update update Clients
// @Summary      update Clients
// @Description  API for update Clients
// @Tags         Clients
// @Security     Bearer
// @Param 	     payload body request.ClientsUpdateRequest true "Required payload"
// @Param        id path string true "Clients ID"
// @Success      200  {object}  response.Response
// @Failure      400  {object}  response.BadRequestError
// @Failure      401  {object}  response.UnauthorizedError
// @Failure      500  {object}  response.InternalServerError
// @Router       /clients/{id} [put]
func (_i *clientsController) Update(c *fiber.Ctx) error {
	idStr := c.Params("id")
	id, err := uuid.Parse(idStr)
	if err != nil {
		return err
	}

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

	err = _i.clientsService.Update(id, *req)
	if err != nil {
		return err
	}

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

// Delete delete Clients
// @Summary      delete Clients
// @Description  API for delete Clients
// @Tags         Clients
// @Security     Bearer
// @Param        id path string true "Clients ID"
// @Success      200  {object}  response.Response
// @Failure      400  {object}  response.BadRequestError
// @Failure      401  {object}  response.UnauthorizedError
// @Failure      500  {object}  response.InternalServerError
// @Router       /clients/{id} [delete]
func (_i *clientsController) Delete(c *fiber.Ctx) error {
	idStr := c.Params("id")
	id, err := uuid.Parse(idStr)
	if err != nil {
		return err
	}

	err = _i.clientsService.Delete(id)
	if err != nil {
		return err
	}

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