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 ebooksController struct {
	ebooksService service.EbooksService
	Log           zerolog.Logger
}

type EbooksController interface {
	All(c *fiber.Ctx) error
	Show(c *fiber.Ctx) error
	ShowBySlug(c *fiber.Ctx) error
	Save(c *fiber.Ctx) error
	SavePdfFile(c *fiber.Ctx) error
	SaveThumbnail(c *fiber.Ctx) error
	Update(c *fiber.Ctx) error
	Delete(c *fiber.Ctx) error
	SummaryStats(c *fiber.Ctx) error
	DownloadPdf(c *fiber.Ctx) error
}

func NewEbooksController(ebooksService service.EbooksService, log zerolog.Logger) EbooksController {
	return &ebooksController{
		ebooksService: ebooksService,
		Log:           log,
	}
}

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

	reqContext := request.EbooksQueryRequestContext{
		Title:       c.Query("title"),
		Description: c.Query("description"),
		AuthorId:    c.Query("authorId"),
		Category:    c.Query("category"),
		Tags:        c.Query("tags"),
		MinPrice:    c.Query("minPrice"),
		MaxPrice:    c.Query("maxPrice"),
		StatusId:    c.Query("statusId"),
		IsPublished: c.Query("isPublished"),
	}
	req := reqContext.ToParamRequest()
	req.Pagination = paginate

	ebooksData, paging, err := _i.ebooksService.All(req)
	if err != nil {
		return err
	}

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

// Show Ebook
// @Summary      Get one Ebook
// @Description  API for getting one Ebook
// @Tags         Ebooks
// @Security     Bearer
// @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       /ebooks/{id} [get]
func (_i *ebooksController) Show(c *fiber.Ctx) error {
	id, err := strconv.ParseUint(c.Params("id"), 10, 0)
	if err != nil {
		return err
	}

	ebookData, err := _i.ebooksService.Show(uint(id))
	if err != nil {
		return err
	}

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

// ShowBySlug Ebook
// @Summary      Get one Ebook by slug
// @Description  API for getting one Ebook by slug
// @Tags         Ebooks
// @Security     Bearer
// @Param        slug path string true "Ebook Slug"
// @Success      200  {object}  response.Response
// @Failure      400  {object}  response.BadRequestError
// @Failure      401  {object}  response.UnauthorizedError
// @Failure      500  {object}  response.InternalServerError
// @Router       /ebooks/slug/{slug} [get]
func (_i *ebooksController) ShowBySlug(c *fiber.Ctx) error {
	slug := c.Params("slug")

	ebookData, err := _i.ebooksService.ShowBySlug(slug)
	if err != nil {
		return err
	}

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

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

	authToken := c.Get("Authorization")

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

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

// SavePdfFile Ebook
// @Summary      Save PDF File Ebook
// @Description  API for Save PDF File of Ebook
// @Tags         Ebooks
// @Security     Bearer
// @Produce      json
// @Param        X-Csrf-Token header string true "Insert the X-Csrf-Token"
// @Param        file formData file true "Upload PDF file"
// @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       /ebooks/pdf/{id} [post]
func (_i *ebooksController) SavePdfFile(c *fiber.Ctx) error {
	id, err := strconv.ParseUint(c.Params("id"), 10, 0)
	if err != nil {
		return err
	}

	err = _i.ebooksService.SavePdfFile(c, uint(id))
	if err != nil {
		return err
	}

	return utilRes.Resp(c, utilRes.Response{
		Success:  true,
		Messages: utilRes.Messages{"PDF file of Ebook successfully uploaded"},
	})
}

// SaveThumbnail Ebook
// @Summary      Save Thumbnail Ebook
// @Description  API for Save Thumbnail of Ebook
// @Tags         Ebooks
// @Security     Bearer
// @Produce      json
// @Param        X-Csrf-Token header string true "Insert the X-Csrf-Token"
// @Param        files formData file true "Upload thumbnail"
// @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       /ebooks/thumbnail/{id} [post]
func (_i *ebooksController) SaveThumbnail(c *fiber.Ctx) error {
	id, err := strconv.ParseUint(c.Params("id"), 10, 0)
	if err != nil {
		return err
	}

	err = _i.ebooksService.SaveThumbnail(c, uint(id))
	if err != nil {
		return err
	}

	return utilRes.Resp(c, utilRes.Response{
		Success:  true,
		Messages: utilRes.Messages{"Thumbnail of Ebook successfully uploaded"},
	})
}

// Update Ebook
// @Summary      Update Ebook
// @Description  API for update Ebook
// @Tags         Ebooks
// @Security     Bearer
// @Param        X-Csrf-Token header string true "Insert the X-Csrf-Token"
// @Param 	     payload body request.EbooksUpdateRequest true "Required payload"
// @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       /ebooks/{id} [put]
func (_i *ebooksController) Update(c *fiber.Ctx) error {
	id, err := strconv.ParseUint(c.Params("id"), 10, 0)
	if err != nil {
		return err
	}

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

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

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

// Delete Ebook
// @Summary      Delete Ebook
// @Description  API for delete Ebook
// @Tags         Ebooks
// @Security     Bearer
// @Param        X-Csrf-Token header string true "Insert the X-Csrf-Token"
// @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       /ebooks/{id} [delete]
func (_i *ebooksController) Delete(c *fiber.Ctx) error {
	id, err := strconv.ParseUint(c.Params("id"), 10, 0)
	if err != nil {
		return err
	}

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

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

// SummaryStats Ebook
// @Summary      SummaryStats Ebook
// @Description  API for Summary Stats of Ebook
// @Tags         Ebooks
// @Security     Bearer
// @Param        Authorization header string false "Insert your access token" default(Bearer <Add access token here>)
// @Success      200  {object}  response.Response
// @Failure      400  {object}  response.BadRequestError
// @Failure      401  {object}  response.UnauthorizedError
// @Failure      500  {object}  response.InternalServerError
// @Router       /ebooks/statistic/summary [get]
func (_i *ebooksController) SummaryStats(c *fiber.Ctx) error {
	authToken := c.Get("Authorization")

	response, err := _i.ebooksService.SummaryStats(authToken)
	if err != nil {
		return err
	}

	return utilRes.Resp(c, utilRes.Response{
		Success:  true,
		Messages: utilRes.Messages{"Summary Stats of Ebooks successfully retrieved"},
		Data:     response,
	})
}

// DownloadPdf Ebook
// @Summary      Download PDF Ebook
// @Description  API for Download PDF of Ebook
// @Tags         Ebooks
// @Security     Bearer
// @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       /ebooks/download/{id} [get]
func (_i *ebooksController) DownloadPdf(c *fiber.Ctx) error {
	id, err := strconv.ParseUint(c.Params("id"), 10, 0)
	if err != nil {
		return err
	}

	err = _i.ebooksService.DownloadPdf(c, uint(id))
	if err != nil {
		return err
	}

	return nil
}
