package org.raddatz.familienarchiv.ocr;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.raddatz.familienarchiv.exception.DomainException;
import org.raddatz.familienarchiv.exception.ErrorCode;
import org.raddatz.familienarchiv.ocr.OcrJobDocumentRepository;
import org.raddatz.familienarchiv.ocr.OcrJobRepository;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.UUID;

@Service
@RequiredArgsConstructor
@Slf4j
public class OcrBatchService {

    private final OcrHealthClient ocrHealthClient;
    private final OcrJobRepository ocrJobRepository;
    private final OcrJobDocumentRepository ocrJobDocumentRepository;
    private final OcrAsyncRunner ocrAsyncRunner;

    public UUID startBatch(List<UUID> documentIds, UUID userId) {
        if (!ocrHealthClient.isHealthy()) {
            throw DomainException.internal(ErrorCode.OCR_SERVICE_UNAVAILABLE,
                    "OCR service is not available");
        }

        OcrJob job = OcrJob.builder()
                .totalDocuments(documentIds.size())
                .createdBy(userId)
                .status(OcrJobStatus.PENDING)
                .build();
        job = ocrJobRepository.save(job);

        for (UUID docId : documentIds) {
            OcrJobDocument jobDoc = OcrJobDocument.builder()
                    .jobId(job.getId())
                    .documentId(docId)
                    .status(OcrDocumentStatus.PENDING)
                    .build();
            ocrJobDocumentRepository.save(jobDoc);
        }

        ocrAsyncRunner.runBatch(job.getId(), userId);
        return job.getId();
    }
}
