package controller

import (
	"campaign-pool-be/app/module/ebooks/request"
	"campaign-pool-be/app/module/ebooks/service"
	"campaign-pool-be/utils/paginator"
	"strconv"

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

	utilRes "campaign-pool-be/utils/response"
	utilVal "campaign-pool-be/utils/validator"
)

type ebookRatingsController struct {
	ratingsService service.EbookRatingsService
	Log            zerolog.Logger
}

type EbookRatingsController interface {
	GetAll(c *fiber.Ctx) error
	GetByEbookId(c *fiber.Ctx) error
	GetByUserId(c *fiber.Ctx) error
	GetEbookRatingSummary(c *fiber.Ctx) error
	Create(c *fiber.Ctx) error
	Update(c *fiber.Ctx) error
	Delete(c *fiber.Ctx) error
	GetRatingStats(c *fiber.Ctx) error
}

func NewEbookRatingsController(ratingsService service.EbookRatingsService, log zerolog.Logger) EbookRatingsController {
	return &ebookRatingsController{
		ratingsService: ratingsService,
		Log:            log,
	}
}

// GetAll Ratings
// @Summary      Get all Ebook Ratings
// @Description  API for getting all Ebook Ratings
// @Tags         Ebook Ratings
// @Security     Bearer
// @Param        X-Client-Key header string true "Insert the X-Client-Key"
// @Param 	     req query request.EbookRatingsQueryRequest 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       /ebook-ratings [get]
func (_i *ebookRatingsController) GetAll(c *fiber.Ctx) error {
	paginate, err := paginator.Paginate(c)
	if err != nil {
		return err
	}

	reqContext := request.EbookRatingsQueryRequestContext{
		EbookId:    c.Query("ebookId"),
		UserId:     c.Query("userId"),
		Rating:     c.Query("rating"),
		IsVerified: c.Query("isVerified"),
		StatusId:   c.Query("statusId"),
	}
	req := reqContext.ToParamRequest()
	req.Pagination = paginate

	ratingsData, paging, err := _i.ratingsService.GetAll(req)
	if err != nil {
		return err
	}

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

// GetByEbookId Ratings
// @Summary      Get ratings by ebook ID
// @Description  API for getting ratings by ebook ID
// @Tags         Ebook Ratings
// @Security     Bearer
// @Param        X-Client-Key header string true "Insert the X-Client-Key"
// @Param        id path int true "Ebook ID"
// @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       /ebook-ratings/ebook/{id} [get]
func (_i *ebookRatingsController) GetByEbookId(c *fiber.Ctx) error {
	id, err := strconv.ParseUint(c.Params("id"), 10, 0)
	if err != nil {
		return err
	}

	paginate, err := paginator.Paginate(c)
	if err != nil {
		return err
	}

	ratingsData, paging, err := _i.ratingsService.GetByEbookId(uint(id), paginate)
	if err != nil {
		return err
	}

	return utilRes.Resp(c, utilRes.Response{
		Success:  true,
		Messages: utilRes.Messages{"Ebook ratings successfully retrieved"},
		Data:     ratingsData,
		Meta:     paging,
	})
}

// GetByUserId Ratings
// @Summary      Get user ratings
// @Description  API for getting user ratings
// @Tags         Ebook Ratings
// @Security     Bearer
// @Param        X-Client-Key header string true "Insert the X-Client-Key"
// @Param        Authorization header string false "Insert your access token" default(Bearer <Add access token here>)
// @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       /ebook-ratings/user [get]
func (_i *ebookRatingsController) GetByUserId(c *fiber.Ctx) error {
	paginate, err := paginator.Paginate(c)
	if err != nil {
		return err
	}

	authToken := c.Get("Authorization")

	ratingsData, paging, err := _i.ratingsService.GetByUserId(authToken, paginate)
	if err != nil {
		return err
	}

	return utilRes.Resp(c, utilRes.Response{
		Success:  true,
		Messages: utilRes.Messages{"User ratings successfully retrieved"},
		Data:     ratingsData,
		Meta:     paging,
	})
}

// GetEbookRatingSummary Ratings
// @Summary      Get ebook rating summary
// @Description  API for getting ebook rating summary with stats and recent reviews
// @Tags         Ebook Ratings
// @Security     Bearer
// @Param        X-Client-Key header string true "Insert the X-Client-Key"
// @Param        id path int true "Ebook ID"
// @Success      200  {object}  response.Response
// @Failure      400  {object}  response.BadRequestError
// @Failure      401  {object}  response.UnauthorizedError
// @Failure      500  {object}  response.InternalServerError
// @Router       /ebook-ratings/summary/{id} [get]
func (_i *ebookRatingsController) GetEbookRatingSummary(c *fiber.Ctx) error {
	id, err := strconv.ParseUint(c.Params("id"), 10, 0)
	if err != nil {
		return err
	}

	summaryData, err := _i.ratingsService.GetEbookRatingSummary(uint(id))
	if err != nil {
		return err
	}

	return utilRes.Resp(c, utilRes.Response{
		Success:  true,
		Messages: utilRes.Messages{"Ebook rating summary successfully retrieved"},
		Data:     summaryData,
	})
}

// Create Rating
// @Summary      Create ebook rating
// @Description  API for creating ebook rating
// @Tags         Ebook Ratings
// @Security     Bearer
// @Param        X-Csrf-Token header string true "Insert the X-Csrf-Token"
// @Param        Authorization header string false "Insert your access token" default(Bearer <Add access token here>)
// @Param 	     payload body request.EbookRatingsCreateRequest true "Required payload"
// @Success      200  {object}  response.Response
// @Failure      400  {object}  response.BadRequestError
// @Failure      401  {object}  response.UnauthorizedError
// @Failure      500  {object}  response.InternalServerError
// @Router       /ebook-ratings [post]
func (_i *ebookRatingsController) Create(c *fiber.Ctx) error {
	req := new(request.EbookRatingsCreateRequest)
	if err := utilVal.ParseAndValidate(c, req); err != nil {
		return err
	}

	authToken := c.Get("Authorization")

	dataResult, err := _i.ratingsService.Create(*req, authToken)
	if err != nil {
		return err
	}

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

// Update Rating
// @Summary      Update ebook rating
// @Description  API for updating ebook rating
// @Tags         Ebook Ratings
// @Security     Bearer
// @Param        X-Csrf-Token header string true "Insert the X-Csrf-Token"
// @Param        Authorization header string false "Insert your access token" default(Bearer <Add access token here>)
// @Param 	     payload body request.EbookRatingsUpdateRequest true "Required payload"
// @Param        id path int true "Rating ID"
// @Success      200  {object}  response.Response
// @Failure      400  {object}  response.BadRequestError
// @Failure      401  {object}  response.UnauthorizedError
// @Failure      500  {object}  response.InternalServerError
// @Router       /ebook-ratings/{id} [put]
func (_i *ebookRatingsController) Update(c *fiber.Ctx) error {
	id, err := strconv.ParseUint(c.Params("id"), 10, 0)
	if err != nil {
		return err
	}

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

	authToken := c.Get("Authorization")

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

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

// Delete Rating
// @Summary      Delete ebook rating
// @Description  API for deleting ebook rating
// @Tags         Ebook Ratings
// @Security     Bearer
// @Param        X-Csrf-Token header string true "Insert the X-Csrf-Token"
// @Param        Authorization header string false "Insert your access token" default(Bearer <Add access token here>)
// @Param        id path int true "Rating ID"
// @Success      200  {object}  response.Response
// @Failure      400  {object}  response.BadRequestError
// @Failure      401  {object}  response.UnauthorizedError
// @Failure      500  {object}  response.InternalServerError
// @Router       /ebook-ratings/{id} [delete]
func (_i *ebookRatingsController) Delete(c *fiber.Ctx) error {
	id, err := strconv.ParseUint(c.Params("id"), 10, 0)
	if err != nil {
		return err
	}

	authToken := c.Get("Authorization")

	err = _i.ratingsService.Delete(uint(id), authToken)
	if err != nil {
		return err
	}

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

// GetRatingStats Ratings
// @Summary      Get ebook rating statistics
// @Description  API for getting ebook rating statistics
// @Tags         Ebook Ratings
// @Security     Bearer
// @Param        X-Client-Key header string true "Insert the X-Client-Key"
// @Param        id path int true "Ebook ID"
// @Success      200  {object}  response.Response
// @Failure      400  {object}  response.BadRequestError
// @Failure      401  {object}  response.UnauthorizedError
// @Failure      500  {object}  response.InternalServerError
// @Router       /ebook-ratings/stats/{id} [get]
func (_i *ebookRatingsController) GetRatingStats(c *fiber.Ctx) error {
	id, err := strconv.ParseUint(c.Params("id"), 10, 0)
	if err != nil {
		return err
	}

	statsData, err := _i.ratingsService.GetRatingStats(uint(id))
	if err != nil {
		return err
	}

	return utilRes.Resp(c, utilRes.Response{
		Success:  true,
		Messages: utilRes.Messages{"Ebook rating statistics successfully retrieved"},
		Data:     statsData,
	})
}
