package task

import (
	"context"

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

	cardapp "github.com/break/junhong_cmp_fiber/internal/application/cardobservation"
	"github.com/break/junhong_cmp_fiber/pkg/errors"
)

// CardObservationSeriesHandler 处理固定零重试的卡观测序列尝试。
type CardObservationSeriesHandler struct {
	service *cardapp.SeriesAttemptService
	logger  *zap.Logger
}

// NewCardObservationSeriesHandler 创建卡观测序列任务处理器。
func NewCardObservationSeriesHandler(service *cardapp.SeriesAttemptService, logger *zap.Logger) *CardObservationSeriesHandler {
	return &CardObservationSeriesHandler{service: service, logger: logger}
}

// Handle 解析结构化载荷并执行单次观测。
func (h *CardObservationSeriesHandler) Handle(ctx context.Context, task *asynq.Task) error {
	if h == nil || h.service == nil {
		return errors.New(errors.CodeInternalError, "卡观测序列任务服务未配置")
	}
	var payload cardapp.SeriesTaskPayload
	if err := sonic.Unmarshal(task.Payload(), &payload); err != nil {
		h.logger.Error("解析卡观测序列任务载荷失败", zap.Error(err))
		return errors.Wrap(errors.CodeInvalidParam, err, "卡观测序列任务载荷无法解析")
	}
	if err := h.service.Execute(ctx, payload); err != nil {
		h.logger.Warn("卡观测序列当前尝试失败",
			zap.String("series_id", payload.SeriesID), zap.Int("attempt", payload.Attempt), zap.Error(err))
		return err
	}
	return nil
}
