package records

import (
	"context"
	"fmt"

	"github.com/nexuscrm/kernel/pkg/logging"
	"github.com/nexuscrm/kernel/pkg/ports"
	"github.com/nexuscrm/shared/pkg/models"
)

// BulkService orchestrates Bulk API v2 job management
type BulkService struct {
	repo   ports.BulkRepository
	logger *logging.Logger
}

// NewBulkService creates a new BulkService
func NewBulkService(repo ports.BulkRepository, logger *logging.Logger) *BulkService {
	return &BulkService{
		repo:   repo,
		logger: logger,
	}
}

// CreateJob creates a new bulk ingest job
func (s *BulkService) CreateJob(ctx context.Context, job *models.BulkJob) error {
	s.logger.Info(fmt.Sprintf("Creating bulk job for object %s operation %s", job.Object, job.Operation))
	return s.repo.CreateJob(ctx, job)
}

// GetBatches retrieves all batches for a job
func (s *BulkService) GetBatches(ctx context.Context, jobID string) ([]*models.BulkBatch, error) {
	return s.repo.GetBatches(ctx, jobID)
}

// GetJob retrieves a job by ID
func (s *BulkService) GetJob(ctx context.Context, jobID string) (*models.BulkJob, error) {
	return s.repo.GetJob(ctx, jobID)
}

// UpdateJob updates the entire job record
func (s *BulkService) UpdateJob(ctx context.Context, job *models.BulkJob) error {
	s.logger.Info(fmt.Sprintf("Updating bulk job %s", job.ID))
	return s.repo.UpdateJob(ctx, job)
}

func (s *BulkService) CreateBatchIfJobOpen(ctx context.Context, batch *models.BulkBatch) (ports.BulkBatchAdmissionOutcome, error) {
	return s.repo.CreateBatchIfJobOpen(ctx, batch)
}

func (s *BulkService) AcceptIngestJob(ctx context.Context, jobID string) (bool, error) {
	return s.repo.AcceptIngestJob(ctx, jobID)
}

func (s *BulkService) AbortIngestJob(ctx context.Context, jobID string) (bool, error) {
	return s.repo.AbortIngestJob(ctx, jobID)
}

func (s *BulkService) CheckIngestWorkerReady(ctx context.Context) error {
	return s.repo.VerifyActiveWorker(ctx, RuntimeBulkIngestWorkFamily)
}
