/**
 * Processor for "ocr" jobs.
 * Calls the PaymentOCR Python service with the uploaded files.
 */
import axios from "axios";
import FormData from "form-data";

const OCR_BASE_URL =
  process.env.OCR_SERVICE_BASE_URL || "http://localhost:5003";

export interface OcrProcessorInput {
  files: { originalname: string; bufferBase64: string; mimetype: string }[];
}

export async function runOcrProcessor(
  input: OcrProcessorInput
): Promise<any[]> {
  const { files } = input;

  const form = new FormData();
  for (const f of files) {
    const buf = Buffer.from(f.bufferBase64, "base64");
    form.append("files", buf, {
      filename: f.originalname,
      contentType: f.mimetype,
      knownLength: buf.length,
    });
  }

  const resp = await axios.post<{ rows: any[] }>(
    `${OCR_BASE_URL}/extract/json`,
    form,
    {
      headers: form.getHeaders(),
      maxBodyLength: Infinity,
      maxContentLength: Infinity,
      timeout: 180_000, // OCR can be heavy; 3-minute limit
    }
  );

  return resp.data?.rows ?? [];
}
