import type { ErrorHandler } from 'hono';
import { ZodError } from 'zod';

import { logger } from '@/shared/logger';
import { HttpError } from '@/shared/http/errors';

export const errorHandler: ErrorHandler = (err, c) => {
  if (err instanceof HttpError) {
    return c.json(
      { error: err.message, code: err.code },
      err.status as 400 | 401 | 403 | 404 | 409,
    );
  }
  if (err instanceof ZodError) {
    return c.json({ error: 'validation_error', code: 'bad_request', issues: err.issues }, 400);
  }
  const cause = (err as Error & { cause?: unknown }).cause;
  const causeMessage = cause instanceof Error ? cause.message : cause !== undefined ? String(cause) : undefined;
  logger.error('unhandled', { message: err.message, cause: causeMessage, stack: err.stack });
  return c.json({ error: 'internal_error', code: 'internal' }, 500);
};
