import { Context } from 'hono';
import { HTTPException } from 'hono/http-exception';
import { ZodError } from 'zod';
import { appConfig } from '../config';
import { logger } from '../utils/logger';

export const errorHandler = (err: Error, c: Context) => {
  logger.error('Error:', err);
  
  // Handle Hono HTTP exceptions
  if (err instanceof HTTPException) {
    return c.json(
      { error: err.message },
      err.status
    );
  }
  
  // Handle Zod validation errors
  if (err instanceof ZodError) {
    return c.json(
      {
        error: 'Validation error',
        details: err.errors.map(e => ({
          path: e.path.join('.'),
          message: e.message,
        })),
      },
      400
    );
  }
  
  // Handle Prisma errors
  if (err.constructor.name === 'PrismaClientKnownRequestError') {
    const prismaError = err as any;
    
    if (prismaError.code === 'P2002') {
      return c.json(
        { error: 'Duplicate entry' },
        400
      );
    }
    
    if (prismaError.code === 'P2025') {
      return c.json(
        { error: 'Record not found' },
        404
      );
    }
  }
  
  // Default error response
  return c.json(
    {
      error: 'Internal server error',
      message: appConfig.env === 'development' ? err.message : undefined,
    },
    500
  );
};