package admin

import (
	"math"
	"strconv"

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

	shopapp "github.com/break/junhong_cmp_fiber/internal/application/shop"
	walletapp "github.com/break/junhong_cmp_fiber/internal/application/wallet"
	"github.com/break/junhong_cmp_fiber/internal/model/dto"
	shopquery "github.com/break/junhong_cmp_fiber/internal/query/shop"
	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
	createService       *shopapp.CreateService
	updateService       *shopapp.UpdateService
	ownerQuery          *shopquery.BusinessOwnerQuery
	changeCreditService *walletapp.ChangeCreditService
	validator           *validator.Validate
}

// SetChangeCreditService 注入既有店铺实际信用额度调整用例。
func (h *ShopHandler) SetChangeCreditService(service *walletapp.ChangeCreditService) {
	h.changeCreditService = service
}

// SetCreateService 注入店铺创建 Application 事务脚本。
func (h *ShopHandler) SetCreateService(service *shopapp.CreateService) {
	h.createService = service
}

// SetUpdateService 注入店铺更新 Application 事务脚本。
func (h *ShopHandler) SetUpdateService(service *shopapp.UpdateService) {
	h.updateService = service
}

// SetBusinessOwnerQuery 注入店铺业务员归属 Query。
func (h *ShopHandler) SetBusinessOwnerQuery(query *shopquery.BusinessOwnerQuery) {
	h.ownerQuery = query
}

// 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)

	if h.ownerQuery == nil {
		return errors.New(errors.CodeInternalError, "店铺业务员查询服务未配置")
	}
	shops, total, err := h.ownerQuery.List(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.Bool("page_present", c.Context().QueryArgs().Has("page")),
		zap.Bool("page_size_present", c.Context().QueryArgs().Has("page_size")),
		zap.Error(err),
	)
}

// Detail 查询店铺详情。
// GET /api/admin/shops/:id
func (h *ShopHandler) Detail(c *fiber.Ctx) error {
	id, err := strconv.ParseUint(c.Params("id"), 10, 64)
	if err != nil || id == 0 || id > math.MaxInt64 {
		return errors.New(errors.CodeInvalidParam)
	}
	if h.ownerQuery == nil {
		return errors.New(errors.CodeInternalError, "店铺业务员查询服务未配置")
	}
	result, err := h.ownerQuery.Detail(c.UserContext(), uint(id))
	if err != nil {
		return err
	}
	return response.Success(c, result)
}

// UpdateCreditLimit 调整既有店铺代理主钱包实际信用额度。
// PUT /api/admin/shops/:id/credit-limit
func (h *ShopHandler) UpdateCreditLimit(c *fiber.Ctx) error {
	id, err := strconv.ParseUint(c.Params("id"), 10, 64)
	if err != nil || id == 0 || id > math.MaxInt64 {
		return errors.New(errors.CodeInvalidParam)
	}
	var request dto.UpdateShopCreditLimitRequest
	if err := c.BodyParser(&request); err != nil {
		return errors.New(errors.CodeInvalidParam)
	}
	if h.validator == nil || h.validator.Struct(&request) != nil {
		return errors.New(errors.CodeInvalidParam)
	}
	if h.changeCreditService == nil {
		return errors.New(errors.CodeInternalError, "店铺信用额度服务未配置")
	}
	result, err := h.changeCreditService.Execute(c.UserContext(), uint(id), *request.CreditEnabled, *request.CreditLimit, *request.Version)
	if err != nil {
		return err
	}
	return response.Success(c, result)
}

// BusinessOwnerCandidates 查询当前可人工绑定的平台业务员候选。
// GET /api/admin/shops/business-owner-candidates
func (h *ShopHandler) BusinessOwnerCandidates(c *fiber.Ctx) error {
	var request dto.ShopBusinessOwnerCandidateRequest
	if err := c.QueryParser(&request); err != nil {
		h.logBusinessOwnerCandidateValidationFailure(c, err)
		return errors.New(errors.CodeInvalidParam)
	}
	if h.validator == nil {
		return errors.New(errors.CodeInternalError, "业务员候选校验器未配置")
	}
	if err := h.validator.Struct(request); err != nil {
		h.logBusinessOwnerCandidateValidationFailure(c, err)
		return errors.New(errors.CodeInvalidParam)
	}
	if h.ownerQuery == nil {
		return errors.New(errors.CodeInternalError, "店铺业务员查询服务未配置")
	}
	items, total, page, pageSize, err := h.ownerQuery.Candidates(c.UserContext(), request)
	if err != nil {
		return err
	}
	return response.SuccessWithPagination(c, items, total, page, pageSize)
}

func (h *ShopHandler) logBusinessOwnerCandidateValidationFailure(c *fiber.Ctx, err error) {
	logger.GetAppLogger().Warn("店铺业务员候选参数验证失败",
		zap.String("method", c.Method()),
		zap.String("path", c.Path()),
		zap.Bool("keyword_present", c.Context().QueryArgs().Has("keyword")),
		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, "请求参数解析失败")
	}
	if h.validator == nil {
		return errors.New(errors.CodeInternalError, "店铺创建校验器未配置")
	}
	if err := h.validator.Struct(&req); err != nil {
		logger.GetAppLogger().Warn("店铺创建参数验证失败",
			zap.String("method", c.Method()), zap.String("path", c.Path()), zap.Error(err))
		return errors.New(errors.CodeInvalidParam)
	}

	createService := h.createService
	if createService == nil {
		return errors.New(errors.CodeInternalError, "店铺创建服务未配置")
	}
	shop, err := createService.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, "请求参数解析失败")
	}
	if h.validator == nil {
		return errors.New(errors.CodeInternalError, "店铺更新校验器未配置")
	}
	if err := h.validator.Struct(&req); err != nil {
		logger.GetAppLogger().Warn("店铺更新参数验证失败",
			zap.String("method", c.Method()), zap.String("path", c.Path()), zap.Error(err))
		return errors.New(errors.CodeInvalidParam)
	}

	if h.updateService == nil {
		return errors.New(errors.CodeInternalError, "店铺更新服务未配置")
	}
	shop, err := h.updateService.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)
}
