import { GenericError } from './generic';
import { ErrorCategory } from '#constants/errors';

/**
 * Type guards for error narrowing
 * These functions enable type-safe error handling in catch blocks
 */

/**
 * Check if error is a validation error
 */
export function isValidationError(error: GenericError): error is GenericError & { code: 'VALIDATION_ERROR' } {
	return error.code === 'VALIDATION_ERROR';
}

/**
 * Check if error is an authentication error
 */
export function isAuthError(error: GenericError): boolean {
	return error.category === ErrorCategory.AUTHENTICATION || error.category === ErrorCategory.AUTHORIZATION;
}

/**
 * Check if error is a not found error
 */
export function isNotFoundError(error: GenericError): boolean {
	return error.category === ErrorCategory.NOT_FOUND;
}

/**
 * Check if error is a conflict error
 */
export function isConflictError(error: GenericError): boolean {
	return error.category === ErrorCategory.CONFLICT;
}

/**
 * Check if error is a database error
 */
export function isDatabaseError(error: GenericError): boolean {
	return error.category === ErrorCategory.DATABASE;
}

/**
 * Check if error is an external service error
 */
export function isExternalServiceError(error: GenericError): boolean {
	return error.category === ErrorCategory.EXTERNAL;
}

/**
 * Check if error is a system error
 */
export function isSystemError(error: GenericError): boolean {
	return error.category === ErrorCategory.SYSTEM;
}

/**
 * Check if error is critical (high or critical severity)
 */
export function isCriticalError(error: GenericError): boolean {
	const severity = error.code;
	return (
		severity === 'INTERNAL_SERVER_ERROR' ||
		severity === 'DATABASE_ERROR' ||
		severity === 'CIRCUIT_BREAKER_OPEN' ||
		severity === 'EXTERNAL_SERVICE_ERROR'
	);
}
