import { Request, Response, NextFunction } from 'express';
import { DatabaseError } from 'pg';
import logger from '../logger';

export class AppError extends Error {
  constructor(public statusCode: number, message: string) {
    super(message);
    this.name = 'AppError';
  }
}

export function errorHandler(
  err: unknown,
  _req: Request,
  res: Response,
  _next: NextFunction,
): void {
  if (err instanceof AppError) {
    res.status(err.statusCode).json({ error: err.message });
    return;
  }
  if (err instanceof DatabaseError && err.code === '23505') {
    res.status(409).json({ error: 'Email already exists' });
    return;
  }
  logger.error(err);
  res.status(500).json({ error: 'Internal server error' });
}
