package admin

import (
	"strconv"

	"github.com/gofiber/fiber/v2"

	"github.com/break/junhong_cmp_fiber/internal/model/dto"
	packageSeriesService "github.com/break/junhong_cmp_fiber/internal/service/package_series"
	"github.com/break/junhong_cmp_fiber/pkg/errors"
	"github.com/break/junhong_cmp_fiber/pkg/response"
)

type PackageSeriesHandler struct {
	service *packageSeriesService.Service
}

func NewPackageSeriesHandler(service *packageSeriesService.Service) *PackageSeriesHandler {
	return &PackageSeriesHandler{service: service}
}

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

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

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

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

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

	return response.Success(c, series)
}

func (h *PackageSeriesHandler) Get(c *fiber.Ctx) error {
	id, err := strconv.ParseUint(c.Params("id"), 10, 64)
	if err != nil {
		return errors.New(errors.CodeInvalidParam, "无效的套餐系列 ID")
	}

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

	return response.Success(c, series)
}

func (h *PackageSeriesHandler) 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.UpdatePackageSeriesRequest
	if err := c.BodyParser(&req); err != nil {
		return errors.New(errors.CodeInvalidParam, "请求参数解析失败")
	}

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

	return response.Success(c, series)
}

func (h *PackageSeriesHandler) 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 *PackageSeriesHandler) 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.UpdatePackageSeriesStatusRequest
	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)
}
