package admin

import (
	"strconv"

	"github.com/go-playground/validator/v10"
	"github.com/gofiber/fiber/v2"
	"go.uber.org/zap"

	"github.com/break/junhong_cmp_fiber/internal/model/dto"
	shopService "github.com/break/junhong_cmp_fiber/internal/service/shop"
	"github.com/break/junhong_cmp_fiber/pkg/constants"
	"github.com/break/junhong_cmp_fiber/pkg/errors"
	"github.com/break/junhong_cmp_fiber/pkg/logger"
	"github.com/break/junhong_cmp_fiber/pkg/response"
)

// ShopHandler 店铺管理处理器。
type ShopHandler struct {
	service   *shopService.Service
	validator *validator.Validate
}

// NewShopHandler 创建店铺管理处理器。
func NewShopHandler(service *shopService.Service, validator *validator.Validate) *ShopHandler {
	return &ShopHandler{service: service, validator: validator}
}

// List 查询店铺列表。
// GET /api/admin/shops
func (h *ShopHandler) List(c *fiber.Ctx) error {
	var req dto.ShopListRequest
	if err := c.QueryParser(&req); err != nil {
		h.logListValidationFailure(c, err)
		return errors.New(errors.CodeInvalidParam)
	}
	if hasExplicitZeroPagination(c, &req) {
		err := errors.New(errors.CodeInvalidParam)
		h.logListValidationFailure(c, err)
		return err
	}
	if h.validator == nil {
		return errors.New(errors.CodeInternalError, "店铺列表校验器未配置")
	}
	if err := h.validator.Struct(&req); err != nil {
		h.logListValidationFailure(c, err)
		return errors.New(errors.CodeInvalidParam)
	}

	normalizeShopListPagination(&req)

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

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

func hasExplicitZeroPagination(c *fiber.Ctx, req *dto.ShopListRequest) bool {
	queryArgs := c.Context().QueryArgs()
	return queryArgs.Has("page") && req.Page == 0 || queryArgs.Has("page_size") && req.PageSize == 0
}

func (h *ShopHandler) logListValidationFailure(c *fiber.Ctx, err error) {
	logger.GetAppLogger().Warn("店铺列表参数验证失败",
		zap.String("method", c.Method()),
		zap.String("path", c.Path()),
		zap.String("query", c.Context().QueryArgs().String()),
		zap.Error(err),
	)
}

func normalizeShopListPagination(req *dto.ShopListRequest) {
	if req.Page == 0 {
		req.Page = constants.DefaultPage
	}
	if req.PageSize == 0 {
		req.PageSize = constants.DefaultPageSize
	}
}

// Create 创建店铺。
// POST /api/admin/shops
func (h *ShopHandler) Create(c *fiber.Ctx) error {
	var req dto.CreateShopRequest
	if err := c.BodyParser(&req); err != nil {
		return errors.New(errors.CodeInvalidParam, "请求参数解析失败")
	}

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

	return response.Success(c, shop)
}

// Update 更新店铺。
// PUT /api/admin/shops/:id
func (h *ShopHandler) 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.UpdateShopRequest
	if err := c.BodyParser(&req); err != nil {
		return errors.New(errors.CodeInvalidParam, "请求参数解析失败")
	}

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

	return response.Success(c, shop)
}

// Delete 删除店铺。
// DELETE /api/admin/shops/:id
func (h *ShopHandler) 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)
}

// Cascade 店铺联级查询
// GET /api/admin/shops/cascade
func (h *ShopHandler) Cascade(c *fiber.Ctx) error {
	var req dto.ShopCascadeRequest
	if err := c.QueryParser(&req); err != nil {
		return errors.New(errors.CodeInvalidParam, "请求参数解析失败")
	}

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

	return response.Success(c, items)
}
