perplexity-hackathon-LawMitra / perplexity_hackathon / src / routes / advocateRoutes.ts
advocateRoutes.ts
Raw
import { Router, Request, Response } from 'express';
import { authenticate, requireRole } from '../middleware/authMiddleware';
import { firebaseService } from '../services/firebaseService';
import { z } from 'zod';

const router = Router();

// Apply authentication middleware to all routes
router.use(authenticate);
router.use(requireRole(['advocate']));

// Get advocate's dashboard data
router.get('/dashboard', async (req: Request, res: Response) => {
  try {
    const [cases, stats] = await Promise.all([
      firebaseService.getAdvocateCases(req.user!.uid),
      firebaseService.getAdvocateStats(req.user!.uid),
    ]);

    res.json({
      success: true,
      data: {
        cases,
        stats,
      },
    });
  } catch (error) {
    console.error('Error fetching dashboard data:', error);
    res.status(500).json({
      success: false,
      error: 'Failed to fetch dashboard data',
    });
  }
});

// Update case status
const updateStatusSchema = z.object({
  status: z.enum(['in_progress', 'resolved']),
});

router.patch('/cases/:caseId/status', async (req: Request, res: Response) => {
  try {
    const { caseId } = req.params;
    const validatedData = updateStatusSchema.parse(req.body);

    await firebaseService.updateCaseStatus(caseId, validatedData.status);

    res.json({
      success: true,
      message: 'Case status updated successfully',
    });
  } catch (error) {
    if (error instanceof z.ZodError) {
      return res.status(400).json({
        success: false,
        error: 'Validation error',
        details: error.errors,
      });
    }

    console.error('Error updating case status:', error);
    res.status(500).json({
      success: false,
      error: 'Failed to update case status',
    });
  }
});

// Add transcript to case
const addTranscriptSchema = z.object({
  transcript: z.string().min(1),
});

router.post('/cases/:caseId/transcripts', async (req: Request, res: Response) => {
  try {
    const { caseId } = req.params;
    const validatedData = addTranscriptSchema.parse(req.body);

    await firebaseService.addTranscript(caseId, validatedData.transcript);

    res.json({
      success: true,
      message: 'Transcript added successfully',
    });
  } catch (error) {
    if (error instanceof z.ZodError) {
      return res.status(400).json({
        success: false,
        error: 'Validation error',
        details: error.errors,
      });
    }

    console.error('Error adding transcript:', error);
    res.status(500).json({
      success: false,
      error: 'Failed to add transcript',
    });
  }
});

export default router;