/**
 * PDF Text Extractor
 * Extracts text content from uploaded PDFs for AI processing.
 */

import fs from 'fs/promises';
import path from 'path';

const UPLOADS_DIR = path.resolve(process.cwd(), 'uploads');

/**
 * Extract text content from a single PDF file.
 * Returns empty string if the file cannot be read or parsed.
 */
export async function extractTextFromPdf(fileId: string): Promise<string> {
  const filePath = path.join(UPLOADS_DIR, fileId);

  try {
    const dataBuffer = await fs.readFile(filePath);
    // Dynamic import to handle pdf-parse's native dependencies gracefully
    const pdfParse = (await import('pdf-parse')).default;
    const data = await pdfParse(dataBuffer);
    return data.text || '';
  } catch (error: any) {
    console.warn(`[PDF-Extractor] Failed to extract text from ${fileId}: ${error.message}`);
    return '';
  }
}

/**
 * Extract and concatenate text from multiple PDF files.
 * Each PDF's text is separated by a clear delimiter.
 */
export async function extractTextFromMultiplePdfs(fileIds: string[]): Promise<string> {
  if (!fileIds || fileIds.length === 0) return '';

  const texts = await Promise.all(fileIds.map(extractTextFromPdf));
  const nonEmptyTexts = texts.filter(t => t.trim().length > 0);

  if (nonEmptyTexts.length === 0) return '';

  return nonEmptyTexts.join('\n\n---\n\n');
}