perplexity-hackathon-LawMitra / perplexity_hackathon / src / routes / documentRoutes.ts
documentRoutes.ts
Raw
import { Router, Request, Response } from 'express';
import { z } from 'zod';
import { documentService } from '../services/documentService';

const router = Router();

// Input validation schema
const documentRequestSchema = z.object({
  type: z.enum(['fir', 'rent_agreement', 'affidavit']),
  details: z.record(z.string(), z.any()),
  language: z.string().min(2).max(10),
});

router.post('/generate-document', async (req: Request, res: Response) => {
  try {
    // Validate input
    const validatedData = documentRequestSchema.parse(req.body);

    // Generate document
    const pdfBuffer = await documentService.generateDocument({
      type: validatedData.type,
      details: validatedData.details,
      language: validatedData.language,
    });

    // Set response headers for PDF download
    res.setHeader('Content-Type', 'application/pdf');
    res.setHeader(
      'Content-Disposition',
      `attachment; filename=${validatedData.type}_${Date.now()}.pdf`
    );

    // Send the PDF
    res.send(pdfBuffer);
  } catch (error) {
    if (error instanceof z.ZodError) {
      return res.status(400).json({
        success: false,
        error: 'Validation error',
        details: error.errors,
      });
    }

    console.error('Error generating document:', error);
    res.status(500).json({
      success: false,
      error: 'Failed to generate document',
    });
  }
});

// Get available fields for a template
router.get('/template-fields/:type', async (req: Request, res: Response) => {
  try {
    const { type } = req.params;
    const fields = await documentService.getTemplateFields(type);
    
    res.json({
      success: true,
      fields,
    });
  } catch (error) {
    console.error('Error getting template fields:', error);
    res.status(500).json({
      success: false,
      error: 'Failed to get template fields',
    });
  }
});

export default router;