package integration

import (
	"context"
	"time"

	gamev1 "hyapp.local/api/proto/game/v1"
	"hyapp/services/cron-service/internal/scheduler"
)

// GameCronClient delegates game-owned background batches to game-service.
type GameCronClient struct {
	client gamev1.GameCronServiceClient
}

// NewGameCronClient creates scheduler handlers backed by game-service gRPC.
func NewGameCronClient(client gamev1.GameCronServiceClient) *GameCronClient {
	return &GameCronClient{client: client}
}

// ProcessLevelEventOutboxBatch relays successful game debit orders into the growth-level system.
func (c *GameCronClient) ProcessLevelEventOutboxBatch(ctx context.Context, req scheduler.BatchRequest) (scheduler.BatchResult, error) {
	resp, err := c.client.ProcessLevelEventOutboxBatch(ctx, gameCronBatchRequest(req))
	if err != nil {
		return scheduler.BatchResult{}, err
	}
	return gameCronBatchResult(resp), nil
}

func gameCronBatchRequest(req scheduler.BatchRequest) *gamev1.CronBatchRequest {
	return &gamev1.CronBatchRequest{
		Meta: &gamev1.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(),
	}
}

func gameCronBatchResult(resp *gamev1.CronBatchResponse) scheduler.BatchResult {
	if resp == nil {
		return scheduler.BatchResult{}
	}
	return scheduler.BatchResult{
		ClaimedCount:   int(resp.GetClaimedCount()),
		ProcessedCount: int(resp.GetProcessedCount()),
		SuccessCount:   int(resp.GetSuccessCount()),
		FailureCount:   int(resp.GetFailureCount()),
		HasMore:        resp.GetHasMore(),
	}
}
