package integration

import (
	"context"
	"time"

	activityv1 "hyapp.local/api/proto/activity/v1"
	"hyapp/services/cron-service/internal/scheduler"
)

// ActivityCronClient delegates activity-owned background batches to activity-service.
type ActivityCronClient struct {
	client activityv1.ActivityCronServiceClient
}

// NewActivityCronClient creates scheduler handlers backed by activity-service gRPC.
func NewActivityCronClient(client activityv1.ActivityCronServiceClient) *ActivityCronClient {
	return &ActivityCronClient{client: client}
}

// ProcessMessageFanoutBatch handles message_fanout_jobs.
func (c *ActivityCronClient) ProcessMessageFanoutBatch(ctx context.Context, req scheduler.BatchRequest) (scheduler.BatchResult, error) {
	resp, err := c.client.ProcessMessageFanoutBatch(ctx, &activityv1.CronBatchRequest{
		Meta: &activityv1.RequestMeta{
			RequestId: req.RunID,
			Caller:    "cron-service",
			SentAtMs:  time.Now().UnixMilli(),
			AppCode:   req.AppCode,
		},
		RunId:     req.RunID,
		WorkerId:  req.WorkerID,
		BatchSize: int32(req.BatchSize),
		LockTtlMs: req.LockTTL.Milliseconds(),
	})
	if err != nil {
		return scheduler.BatchResult{}, err
	}
	return scheduler.BatchResult{
		ClaimedCount:   int(resp.GetClaimedCount()),
		ProcessedCount: int(resp.GetProcessedCount()),
		SuccessCount:   int(resp.GetSuccessCount()),
		FailureCount:   int(resp.GetFailureCount()),
		HasMore:        resp.GetHasMore(),
	}, nil
}
