import { Request, Response, NextFunction } from 'express';
import { Prisma } from '@prisma/client';

export function errorHandler(err: Error, _req: Request, res: Response, _next: NextFunction): void {
  console.error('[Error]', err.message);

  // Prisma unique constraint
  if (err instanceof Prisma.PrismaClientKnownRequestError) {
    if (err.code === 'P2002') {
      res.status(409).json({ error: 'A record with that value already exists' });
      return;
    }
    if (err.code === 'P2025') {
      res.status(404).json({ error: 'Record not found' });
      return;
    }
  }

  // Validation errors surfaced as plain errors with status
  const status = (err as { status?: number }).status || 500;
  res.status(status).json({ error: err.message || 'Internal server error' });
}

// Catch-all 404 for unmatched routes
export function notFound(_req: Request, res: Response): void {
  res.status(404).json({ error: 'Route not found' });
}
