package com.datamate.datamanagement.application;

import com.datamate.common.infrastructure.common.Response;
import com.datamate.datamanagement.infrastructure.client.PdfTextExtractClient;
import com.datamate.datamanagement.infrastructure.client.dto.PdfTextExtractRequest;
import com.datamate.datamanagement.infrastructure.client.dto.PdfTextExtractResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

@Service
@RequiredArgsConstructor
@Slf4j
public class PdfTextExtractAsyncService {
    private final PdfTextExtractClient pdfTextExtractClient;

    @Async
    public void extractPdfText(String datasetId, String fileId) {
        try {
            Response<PdfTextExtractResponse> response = pdfTextExtractClient.extractPdfText(
                new PdfTextExtractRequest(datasetId, fileId)
            );
            if (response == null) {
                log.warn("PdfTextExtract returned null response, datasetId={}, fileId={}", datasetId, fileId);
                return;
            }
            String code = response.getCode();
            if (!"0".equals(code) && !"200".equals(code)) {
                log.warn(
                    "PdfTextExtract failed, datasetId={}, fileId={}, code={}, message={}",
                    datasetId,
                    fileId,
                    code,
                    response.getMessage()
                );
                return;
            }
            PdfTextExtractResponse data = response.getData();
            if (data != null) {
                log.info(
                    "PdfTextExtract succeeded, datasetId={}, fileId={}, textFileId={}",
                    datasetId,
                    fileId,
                    data.getTextFileId()
                );
            } else {
                log.info("PdfTextExtract succeeded, datasetId={}, fileId={}", datasetId, fileId);
            }
        } catch (Exception e) {
            log.error("PdfTextExtract call failed, datasetId={}, fileId={}", datasetId, fileId, e);
        }
    }
}
