package controller

import (
	"math"
	"strconv"

	"gitlab.com/mbugroup/lti-api.git/internal/modules/master/products/dto"
	service "gitlab.com/mbugroup/lti-api.git/internal/modules/master/products/services"
	validation "gitlab.com/mbugroup/lti-api.git/internal/modules/master/products/validations"
	"gitlab.com/mbugroup/lti-api.git/internal/response"

	"github.com/gofiber/fiber/v2"
)

type ProductController struct {
	ProductService service.ProductService
}

func NewProductController(productService service.ProductService) *ProductController {
	return &ProductController{
		ProductService: productService,
	}
}

func (u *ProductController) GetAll(c *fiber.Ctx) error {
	query := &validation.Query{
		Page:              c.QueryInt("page", 1),
		Limit:             c.QueryInt("limit", 10),
		Search:            c.Query("search", ""),
		ProductCategoryID: c.QueryInt("product_category_id", 0),
	}

	if isDepletionParam := c.Query("is_depletion", ""); isDepletionParam != "" {
		value, err := strconv.ParseBool(isDepletionParam)
		if err != nil {
			return fiber.NewError(fiber.StatusBadRequest, "invalid is_depletion value")
		}
		query.IsDepletion = &value
	}

	if includeAllParam := c.Query("include_all", ""); includeAllParam != "" {
		value, err := strconv.ParseBool(includeAllParam)
		if err != nil {
			return fiber.NewError(fiber.StatusBadRequest, "invalid include_all value")
		}
		query.IncludeAll = &value
	}

	if query.Page < 1 || query.Limit < 1 {
		return fiber.NewError(fiber.StatusBadRequest, "page and limit must be greater than 0")
	}

	result, totalResults, err := u.ProductService.GetAll(c, query)
	if err != nil {
		return err
	}

	return c.Status(fiber.StatusOK).
		JSON(response.SuccessWithPaginate[dto.ProductListDTO]{
			Code:    fiber.StatusOK,
			Status:  "success",
			Message: "Get all products successfully",
			Meta: response.Meta{
				Page:         query.Page,
				Limit:        query.Limit,
				TotalPages:   int64(math.Ceil(float64(totalResults) / float64(query.Limit))),
				TotalResults: totalResults,
			},
			Data: dto.ToProductListDTOs(result),
		})
}

func (u *ProductController) GetOne(c *fiber.Ctx) error {
	param := c.Params("id")

	id, err := strconv.Atoi(param)
	if err != nil {
		return fiber.NewError(fiber.StatusBadRequest, "Invalid Id")
	}

	result, err := u.ProductService.GetOne(c, uint(id))
	if err != nil {
		return err
	}

	return c.Status(fiber.StatusOK).
		JSON(response.Success{
			Code:    fiber.StatusOK,
			Status:  "success",
			Message: "Get product successfully",
			Data:    dto.ToProductDetailDTO(*result),
		})
}

func (u *ProductController) CreateOne(c *fiber.Ctx) error {
	req := new(validation.Create)

	if err := c.BodyParser(req); err != nil {
		return fiber.NewError(fiber.StatusBadRequest, "Invalid request body")
	}

	result, err := u.ProductService.CreateOne(c, req)
	if err != nil {
		return err
	}

	return c.Status(fiber.StatusCreated).
		JSON(response.Success{
			Code:    fiber.StatusCreated,
			Status:  "success",
			Message: "Create product successfully",
			Data:    dto.ToProductDetailDTO(*result),
		})
}

func (u *ProductController) UpdateOne(c *fiber.Ctx) error {
	req := new(validation.Update)
	param := c.Params("id")

	id, err := strconv.Atoi(param)
	if err != nil {
		return fiber.NewError(fiber.StatusBadRequest, "Invalid Id")
	}

	if err := c.BodyParser(req); err != nil {
		return fiber.NewError(fiber.StatusBadRequest, "Invalid request body")
	}

	result, err := u.ProductService.UpdateOne(c, req, uint(id))
	if err != nil {
		return err
	}

	return c.Status(fiber.StatusOK).
		JSON(response.Success{
			Code:    fiber.StatusOK,
			Status:  "success",
			Message: "Update product successfully",
			Data:    dto.ToProductDetailDTO(*result),
		})
}

func (u *ProductController) DeleteOne(c *fiber.Ctx) error {
	param := c.Params("id")

	id, err := strconv.Atoi(param)
	if err != nil {
		return fiber.NewError(fiber.StatusBadRequest, "Invalid Id")
	}

	if err := u.ProductService.DeleteOne(c, uint(id)); err != nil {
		return err
	}

	return c.Status(fiber.StatusOK).
		JSON(response.Common{
			Code:    fiber.StatusOK,
			Status:  "success",
			Message: "Delete product successfully",
		})
}
