import { NextRequest, NextResponse } from 'next/server';
import { getSession } from '@/lib/auth';
import { readStorageConfig } from '@/lib/backup-config';

import { pgGetSettings } from '@/lib/postgres/data-access';
import { invoiceExtractionFlow } from '@/ai/flows/invoice-extraction.flow';
import fs from 'fs';
import path from 'path';

async function resolveStorageDir() {
  const settings = await pgGetSettings();
  const deploymentMode = String(settings.deploymentMode || 'local').trim().toLowerCase();
  const customPath = String(settings.documentStoragePath || '').trim();
  const configuredDocumentsPath = String(readStorageConfig().documentsPath || '').trim();

  if (deploymentMode === 'local' && customPath) {
    return path.resolve(customPath);
  }

  if (configuredDocumentsPath) {
    return path.resolve(configuredDocumentsPath, 'purchase-documents');
  }

  return path.join(process.cwd(), 'uploads', 'purchase-documents');
}

export async function POST(request: NextRequest) {
  const session = await getSession();
  if (!session?.user || session.user.role !== 'admin') {
    return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
  }

  const settings = await pgGetSettings();
  const googleApiKey = String(settings.aiInvoiceApiKey || process.env.GOOGLE_API_KEY || process.env.GEMINI_API_KEY || '').trim();
  if (!googleApiKey) {
    return NextResponse.json(
      {
        error: 'AI extraction is not configured. Add the Google / Gemini API key in general settings or set GOOGLE_API_KEY in .env.local, then restart the server if needed.',
      },
      { status: 503 }
    );
  }

  // Check if AI invoice entry is enabled in settings
  if (!settings.aiInvoiceEntryEnabled) {
    return NextResponse.json(
      { error: 'AI invoice entry feature is not enabled' },
      { status: 403 }
    );
  }

  try {
    const body = await request.json();
    const { filePath, transcriptText, language } = body;

    let imageBase64: string | undefined;

    // If filePath is provided, read the file and convert to base64
    if (filePath) {
      const storageDir = await resolveStorageDir();
      const legacyUploadsDir = path.join(process.cwd(), 'uploads', 'purchase-documents');
      const normalizedRaw = String(filePath || '').replace(/^['"]|['"]$/g, '').trim();
      const normalizedInput = normalizedRaw;
      const fullPath = path.isAbsolute(normalizedInput)
        ? path.resolve(normalizedInput)
        : path.resolve(storageDir, normalizedInput);

      // Security: prevent directory traversal and restrict file access to known upload roots.
      const allowedRoots = [path.resolve(storageDir), path.resolve(legacyUploadsDir)];
      const allowed = allowedRoots.some((root) => fullPath.startsWith(root));
      if (!allowed) {
        return NextResponse.json({ error: 'Invalid file path' }, { status: 400 });
      }

      try {
        const fileBuffer = fs.readFileSync(fullPath);
        imageBase64 = fileBuffer.toString('base64');
      } catch (error) {
        return NextResponse.json(
          { error: 'Failed to read uploaded file' },
          { status: 400 }
        );
      }
    }

    // Call the invoice extraction flow
    const result = await invoiceExtractionFlow({
      imageBase64,
      transcriptText,
      language: (language as 'en' | 'ar') || 'ar',
      apiKey: googleApiKey,
    });

    return NextResponse.json({
      success: true,
      data: result,
    });
  } catch (error) {
    console.error('AI extraction error:', error);
    return NextResponse.json(
      {
        error: error instanceof Error ? error.message : 'Failed to extract invoice data',
      },
      { status: 500 }
    );
  }
}
