package admin

import (
	"strconv"

	"github.com/gofiber/fiber/v2"

	"github.com/break/junhong_cmp_fiber/internal/model/dto"
	carrierService "github.com/break/junhong_cmp_fiber/internal/service/carrier"
	"github.com/break/junhong_cmp_fiber/pkg/errors"
	"github.com/break/junhong_cmp_fiber/pkg/response"
)

type CarrierHandler struct {
	service *carrierService.Service
}

func NewCarrierHandler(service *carrierService.Service) *CarrierHandler {
	return &CarrierHandler{service: service}
}

func (h *CarrierHandler) List(c *fiber.Ctx) error {
	var req dto.CarrierListRequest
	if err := c.QueryParser(&req); err != nil {
		return errors.New(errors.CodeInvalidParam, "请求参数解析失败")
	}

	carriers, total, err := h.service.List(c.UserContext(), &req)
	if err != nil {
		return err
	}

	return response.SuccessWithPagination(c, carriers, total, req.Page, req.PageSize)
}

func (h *CarrierHandler) Create(c *fiber.Ctx) error {
	var req dto.CreateCarrierRequest
	if err := c.BodyParser(&req); err != nil {
		return errors.New(errors.CodeInvalidParam, "请求参数解析失败")
	}

	carrier, err := h.service.Create(c.UserContext(), &req)
	if err != nil {
		return err
	}

	return response.Success(c, carrier)
}

func (h *CarrierHandler) Get(c *fiber.Ctx) error {
	id, err := strconv.ParseUint(c.Params("id"), 10, 64)
	if err != nil {
		return errors.New(errors.CodeInvalidParam, "无效的运营商 ID")
	}

	carrier, err := h.service.Get(c.UserContext(), uint(id))
	if err != nil {
		return err
	}

	return response.Success(c, carrier)
}

func (h *CarrierHandler) Update(c *fiber.Ctx) error {
	id, err := strconv.ParseUint(c.Params("id"), 10, 64)
	if err != nil {
		return errors.New(errors.CodeInvalidParam, "无效的运营商 ID")
	}

	var req dto.UpdateCarrierRequest
	if err := c.BodyParser(&req); err != nil {
		return errors.New(errors.CodeInvalidParam, "请求参数解析失败")
	}

	carrier, err := h.service.Update(c.UserContext(), uint(id), &req)
	if err != nil {
		return err
	}

	return response.Success(c, carrier)
}

func (h *CarrierHandler) Delete(c *fiber.Ctx) error {
	id, err := strconv.ParseUint(c.Params("id"), 10, 64)
	if err != nil {
		return errors.New(errors.CodeInvalidParam, "无效的运营商 ID")
	}

	if err := h.service.Delete(c.UserContext(), uint(id)); err != nil {
		return err
	}

	return response.Success(c, nil)
}

func (h *CarrierHandler) UpdateStatus(c *fiber.Ctx) error {
	id, err := strconv.ParseUint(c.Params("id"), 10, 64)
	if err != nil {
		return errors.New(errors.CodeInvalidParam, "无效的运营商 ID")
	}

	var req dto.UpdateCarrierStatusRequest
	if err := c.BodyParser(&req); err != nil {
		return errors.New(errors.CodeInvalidParam, "请求参数解析失败")
	}

	if err := h.service.UpdateStatus(c.UserContext(), uint(id), req.Status); err != nil {
		return err
	}

	return response.Success(c, nil)
}
