package usecase

import (
	"context"
	"strings"
	"time"

	jobdom "haixun-backend/internal/model/job/domain/usecase"
	"haixun-backend/internal/model/publish_analytics/domain/entity"
	domusecase "haixun-backend/internal/model/publish_analytics/domain/usecase"
)

const publishAnalyticsTemplateType = "publish-analytics"

func (u *publishAnalyticsUseCase) ScheduleCheckpoints(ctx context.Context, req domusecase.ScheduleCheckpointsRequest) error {
	if u.jobs == nil {
		return nil
	}
	tenantID := strings.TrimSpace(req.TenantID)
	ownerUID := strings.TrimSpace(req.OwnerUID)
	accountID := strings.TrimSpace(req.AccountID)
	mediaID := strings.TrimSpace(req.MediaID)
	if tenantID == "" || ownerUID == "" || accountID == "" || mediaID == "" {
		return nil
	}
	publishedAt := req.PublishedAt
	if publishedAt <= 0 {
		publishedAt = time.Now().UnixNano()
	}
	permalink := strings.TrimSpace(req.Permalink)
	checkpoints := []struct {
		name  string
		delay time.Duration
	}{
		{entity.Checkpoint1h, time.Hour},
		{entity.Checkpoint24h, 24 * time.Hour},
		{entity.Checkpoint7d, 7 * 24 * time.Hour},
	}
	for _, cp := range checkpoints {
		at := publishedAt + cp.delay.Nanoseconds()
		scheduled := at
		_, _ = u.jobs.CreateRun(ctx, jobdom.CreateRunRequest{
			TemplateType: publishAnalyticsTemplateType,
			Scope:        "threads_account",
			ScopeID:      accountID,
			TenantID:     tenantID,
			OwnerUID:     ownerUID,
			ScheduledAt:  &scheduled,
			Payload: map[string]any{
				"tenant_id":    tenantID,
				"owner_uid":    ownerUID,
				"account_id":   accountID,
				"media_id":     mediaID,
				"permalink":    permalink,
				"published_at": publishedAt,
				"checkpoint":   cp.name,
			},
		})
	}
	return nil
}
