package app

import (
	"strconv"

	"github.com/break/junhong_cmp_fiber/internal/model/dto"
	exchangeService "github.com/break/junhong_cmp_fiber/internal/service/exchange"
	"github.com/break/junhong_cmp_fiber/pkg/errors"
	"github.com/break/junhong_cmp_fiber/pkg/response"
	"github.com/go-playground/validator/v10"
	"github.com/gofiber/fiber/v2"
)

type ClientExchangeHandler struct {
	service   *exchangeService.Service
	validator *validator.Validate
}

func NewClientExchangeHandler(service *exchangeService.Service) *ClientExchangeHandler {
	return &ClientExchangeHandler{service: service, validator: validator.New()}
}

func (h *ClientExchangeHandler) GetPending(c *fiber.Ctx) error {
	var req dto.ClientExchangePendingRequest
	if err := c.QueryParser(&req); err != nil {
		return errors.New(errors.CodeInvalidParam)
	}
	if err := h.validator.Struct(&req); err != nil {
		return errors.New(errors.CodeInvalidParam)
	}

	data, err := h.service.GetPending(c.UserContext(), req.Identifier)
	if err != nil {
		return err
	}
	return response.Success(c, data)
}

func (h *ClientExchangeHandler) SubmitShippingInfo(c *fiber.Ctx) error {
	id, err := strconv.ParseUint(c.Params("id"), 10, 64)
	if err != nil || id == 0 {
		return errors.New(errors.CodeInvalidParam)
	}

	var req dto.ClientShippingInfoRequest
	if err = c.BodyParser(&req); err != nil {
		return errors.New(errors.CodeInvalidParam)
	}
	if err = h.validator.Struct(&req); err != nil {
		return errors.New(errors.CodeInvalidParam)
	}

	if err = h.service.SubmitShippingInfo(c.UserContext(), uint(id), &req); err != nil {
		return err
	}
	return response.Success(c, nil)
}
