package queue

import (
	"context"
	"errors"
	"strconv"

	"github.com/hibiken/asynq"

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

// CardObservationSeriesScheduler 将固定阶梯任务提交到独立队列。
type CardObservationSeriesScheduler struct {
	client *Client
}

// NewCardObservationSeriesScheduler 创建卡观测序列任务调度器。
func NewCardObservationSeriesScheduler(client *Client) *CardObservationSeriesScheduler {
	return &CardObservationSeriesScheduler{client: client}
}

// Enqueue 以稳定 series_id + attempt 任务 ID 零重试入队。
func (s *CardObservationSeriesScheduler) Enqueue(ctx context.Context, payload cardapp.SeriesTaskPayload) error {
	if s == nil || s.client == nil {
		return pkgerrors.New(pkgerrors.CodeInternalError, "卡观测序列队列客户端未配置")
	}
	taskID := "card-series-" + payload.SeriesID + "-" + strconv.Itoa(payload.Attempt)
	err := s.client.EnqueueTask(
		ctx,
		constants.TaskTypeCardObservationSeries,
		payload,
		asynq.TaskID(taskID),
		asynq.ProcessAt(payload.ScheduledAt),
		asynq.MaxRetry(0),
	)
	if errors.Is(err, asynq.ErrTaskIDConflict) {
		return nil
	}
	return err
}

var _ cardapp.SeriesScheduler = (*CardObservationSeriesScheduler)(nil)
