package controller

import (
	"math"
	"strconv"
	"strings"

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

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

type DeliveryOrdersController struct {
	DeliveryOrdersService service.DeliveryOrdersService
}

func NewDeliveryOrdersController(deliveryOrdersService service.DeliveryOrdersService) *DeliveryOrdersController {
	return &DeliveryOrdersController{
		DeliveryOrdersService: deliveryOrdersService,
	}
}

func (u *DeliveryOrdersController) GetAll(c *fiber.Ctx) error {
	parseUintListParam := func(param string) ([]uint, error) {
		if param == "" {
			return nil, nil
		}
		parts := strings.Split(param, ",")
		ids := make([]uint, 0, len(parts))
		for _, part := range parts {
			trimmed := strings.TrimSpace(part)
			if trimmed == "" {
				return nil, strconv.ErrSyntax
			}
			parsed, err := strconv.ParseUint(trimmed, 10, 64)
			if err != nil {
				return nil, err
			}
			ids = append(ids, uint(parsed))
		}
		return ids, nil
	}

	productIDs, err := parseUintListParam(c.Query("product_ids", ""))
	if err != nil {
		return fiber.NewError(fiber.StatusBadRequest, "Invalid product_ids")
	}

	query := &validation.DeliveryOrderQuery{
		Page:        c.QueryInt("page", 1),
		Limit:       c.QueryInt("limit", 10),
		Search:      strings.TrimSpace(c.Query("search", "")),
		ProductIDs:  productIDs,
		Status:      strings.ReplaceAll(strings.TrimSpace(c.Query("status", "")), "_", " "),
		CustomerId:  uint(c.QueryInt("customer_id", 0)),
		MarketingId: uint(c.QueryInt("marketing_id", 0)),
	}

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

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

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

func (u *DeliveryOrdersController) 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.DeliveryOrdersService.GetOne(c, uint(id))
	if err != nil {
		return err
	}

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

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

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

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

	return c.Status(fiber.StatusCreated).
		JSON(response.Success{
			Code:    fiber.StatusCreated,
			Status:  "success",
			Message: "Create delivery products successfully",
			Data:    result,
		})
}

func (u *DeliveryOrdersController) UpdateOne(c *fiber.Ctx) error {
	req := new(validation.DeliveryOrderUpdate)
	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.DeliveryOrdersService.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 deliveryOrders successfully",
			Data:    result,
		})
}
