import { DocumentProcessorServiceClient } from "@google-cloud/documentai";
import logger from "@utils/logger";

export class CpcOcrService {
    private client: DocumentProcessorServiceClient;

    constructor() {
        this.client = new DocumentProcessorServiceClient({
            keyFilename: process.env.GCP_KEY_FILE
        });
    }

    async runDocAIOcr(params: { 
        projectId: string, 
        location: string, 
        processorId: string, 
        fileBuffer: Buffer, 
        mimeType?: string 
    }) {
        const { projectId, location, processorId, fileBuffer, mimeType } = params;
        const name = `projects/${projectId}/locations/${location}/processors/${processorId}`;
        
        logger.info(`[CpcOcrService] Running Document AI OCR for processor: ${processorId}`);

        const request = {
            name,
            rawDocument: {
                content: fileBuffer.toString("base64"),
                mimeType: mimeType || "application/pdf",
            },
        };

        try {
            const [result] = await this.client.processDocument(request);
            const text = result?.document?.text || "";
            return { text };
        } catch (error) {
            logger.error(`[CpcOcrService] Document AI Error: ${error instanceof Error ? error.message : String(error)}`);
            throw error;
        }
    }
}

export const cpcOcrService = new CpcOcrService();
