// Error Helper Utilities
// Common error constructors and handlers

import { DbisError, ErrorCode } from '@/shared/types';
import { logger } from '@/infrastructure/monitoring/logger';

/**
 * Create a validation error
 */
export function createValidationError(message: string, details?: Record<string, unknown>): DbisError {
  return new DbisError(ErrorCode.VALIDATION_ERROR, message, details);
}

/**
 * Create an unauthorized error
 */
export function createUnauthorizedError(message: string = 'Unauthorized access'): DbisError {
  return new DbisError(ErrorCode.UNAUTHORIZED, message);
}

/**
 * Create a not found error
 */
export function createNotFoundError(resource: string, id?: string): DbisError {
  const message = id ? `${resource} with id ${id} not found` : `${resource} not found`;
  return new DbisError(ErrorCode.NOT_FOUND, message);
}

/**
 * Create an internal error
 */
export function createInternalError(message: string, error?: Error): DbisError {
  if (error) {
    logger.error('Internal error', {
      message,
      error: error.message,
      stack: error.stack,
    });
  }
  return new DbisError(ErrorCode.INTERNAL_ERROR, message);
}

/**
 * Handle and log error
 */
export function handleError(error: unknown, context?: string): DbisError {
  if (error instanceof DbisError) {
    return error;
  }

  const errorMessage = error instanceof Error ? error.message : 'Unknown error';
  const fullMessage = context ? `${context}: ${errorMessage}` : errorMessage;

  logger.error('Unhandled error', {
    message: fullMessage,
    error: error instanceof Error ? error.stack : String(error),
    context,
  });

  return createInternalError(fullMessage, error instanceof Error ? error : undefined);
}

