/**
 * OCR Client
 * Calls the Python FastAPI OCR microservice to verify a document image.
 *
 * Usage:
 *   const { verifyDocument } = require('./ocrClient');
 *   const result = await verifyDocument({ imageBase64, backImageBase64, personId, minimumAge });
 */

const axios = require("axios");

const OCR_API_URL = process.env.OCR_API_URL || "http://146.190.152.146:8500";
const OCR_API_KEY = process.env.OCR_API_KEY || "changeme-ocr-secret";

/**
 * @param {object} opts
 * @param {string}  opts.imageBase64       - base64 front of ID (with or without data URI prefix)
 * @param {string} [opts.backImageBase64]  - base64 back of ID (optional, for barcode)
 * @param {string} [opts.personId]         - Django Person UUID — if set, saves to DB
 * @param {number} [opts.minimumAge=21]    - minimum age to check
 *
 * @returns {{
 *   success: boolean,
 *   source: "barcode"|"ocr"|"none",
 *   extracted_name: string,
 *   extracted_dob: string|null,       // "YYYY-MM-DD"
 *   extracted_document_number: string,
 *   is_underage: boolean|null,
 *   age: number|null,
 *   saved_to_db: boolean,
 *   error: string|null
 * }}
 */
// async function verifyDocument({
//     imageBase64,
//     backImageBase64 = null,
//     personRef = null,
//     minimumAge = 21
// }) {
//     const res = await axios.post(
//         `${OCR_API_URL}/verify-document`,
//         {
//             image_base64: imageBase64,
//             back_image_base64: backImageBase64 || undefined,
//             person_ref: personRef || undefined, // ✅ FIXED
//             minimum_age: minimumAge,
//         },
//         {
//             headers: {
//                 "Content-Type": "application/json",
//                 "x-api-key": OCR_API_KEY,
//             },
//             timeout: 30000,
//         }
//     );

//     return res.data;
// }

async function verifyDocument({
    imageBase64,
    backImageBase64 = null,
    selfieBase64 = null,
    personRef = null,
    minimumAge = 18
}) {
    const res = await axios.post(
        `${OCR_API_URL}/verify-document`,
        {
            image_base64: imageBase64,
            back_image_base64: backImageBase64 || undefined,
            selfie_base64: selfieBase64 || undefined,
            person_ref: personRef || undefined,
            minimum_age: minimumAge,
        },
        {
            headers: { "Content-Type": "application/json", "x-api-key": OCR_API_KEY },
            // timeout: 30000,
            timeout: 120000,
        }
    );
    return res.data;
}
module.exports = { verifyDocument };
