package task

import (
	"context"

	"github.com/bytedance/sonic"
	"github.com/hibiken/asynq"
	"go.uber.org/zap"
	"gorm.io/gorm"

	"github.com/break/junhong_cmp_fiber/internal/service/commission_calculation"
)

const (
	TypeCommissionCalculation = "commission:calculate"
)

type CommissionCalculationPayload struct {
	OrderID uint `json:"order_id"`
}

type CommissionCalculationHandler struct {
	db      *gorm.DB
	service *commission_calculation.Service
	logger  *zap.Logger
}

func NewCommissionCalculationHandler(
	db *gorm.DB,
	service *commission_calculation.Service,
	logger *zap.Logger,
) *CommissionCalculationHandler {
	return &CommissionCalculationHandler{
		db:      db,
		service: service,
		logger:  logger,
	}
}

func (h *CommissionCalculationHandler) HandleCommissionCalculation(ctx context.Context, task *asynq.Task) error {
	var payload CommissionCalculationPayload
	if err := sonic.Unmarshal(task.Payload(), &payload); err != nil {
		h.logger.Error("解析佣金计算任务载荷失败",
			zap.Error(err),
			zap.String("task_id", task.ResultWriter().TaskID()),
		)
		return asynq.SkipRetry
	}

	if err := h.service.CalculateCommission(ctx, payload.OrderID); err != nil {
		h.logger.Error("佣金计算失败",
			zap.Uint("order_id", payload.OrderID),
			zap.Error(err),
		)
		return err
	}

	h.logger.Info("佣金计算成功",
		zap.Uint("order_id", payload.OrderID),
	)

	return nil
}
