import { fileURLToPath as __fileURLToPath } from 'url';
import { dirname as __pathDirname } from 'path';
const __filename = __fileURLToPath(import.meta.url);
const __dirname = __pathDirname(__filename);
import { logger } from "../monitoring/logger.js";
import {
  StackMemoryError,
  ErrorCode,
  getErrorMessage,
  SystemError,
  IntegrationError,
  DatabaseError
} from "./index.js";
async function safeExecute(operation, context, defaultValue) {
  try {
    return await operation();
  } catch (error) {
    logger.debug(
      `Silent failure in ${context.component}.${context.operation}`,
      {
        error: getErrorMessage(error),
        ...context.additionalInfo
      }
    );
    return defaultValue;
  }
}
function safeExecuteSync(operation, context, defaultValue) {
  try {
    return operation();
  } catch (error) {
    logger.debug(
      `Silent failure in ${context.component}.${context.operation}`,
      {
        error: getErrorMessage(error),
        ...context.additionalInfo
      }
    );
    return defaultValue;
  }
}
async function executeWithFallback(operation, context) {
  try {
    return await operation();
  } catch (error) {
    logger.warn(`Operation failed: ${context.component}.${context.operation}`, {
      error: getErrorMessage(error),
      ...context.additionalInfo
    });
    return null;
  }
}
function executeWithFallbackSync(operation, context) {
  try {
    return operation();
  } catch (error) {
    logger.warn(`Operation failed: ${context.component}.${context.operation}`, {
      error: getErrorMessage(error),
      ...context.additionalInfo
    });
    return null;
  }
}
function extractError(error) {
  if (error instanceof StackMemoryError) {
    return {
      message: error.message,
      code: error.code,
      isRetryable: error.isRetryable,
      cause: error.cause
    };
  }
  if (error instanceof Error) {
    const nodeError = error;
    return {
      message: error.message,
      code: nodeError.code,
      isRetryable: isNetworkError(error),
      cause: error
    };
  }
  return {
    message: typeof error === "string" ? error : "Unknown error",
    isRetryable: false
  };
}
function isNetworkError(error) {
  if (!(error instanceof Error)) return false;
  const message = error.message.toLowerCase();
  const networkIndicators = [
    "econnrefused",
    "enotfound",
    "timeout",
    "socket hang up",
    "econnreset",
    "epipe",
    "network",
    "fetch failed"
  ];
  return networkIndicators.some((indicator) => message.includes(indicator));
}
function toTypedError(error, fallbackCode = ErrorCode.UNKNOWN_ERROR) {
  if (error instanceof StackMemoryError) {
    return error;
  }
  const extracted = extractError(error);
  return new SystemError(
    extracted.message,
    fallbackCode,
    { originalError: extracted.code },
    extracted.cause
  );
}
function createApiError(response, body, context) {
  const code = response.status === 401 || response.status === 403 ? ErrorCode.LINEAR_AUTH_FAILED : ErrorCode.LINEAR_API_ERROR;
  return new IntegrationError(
    `API error: ${response.status} ${response.statusText}`,
    code,
    {
      status: response.status,
      statusText: response.statusText,
      body,
      ...context
    }
  );
}
function logAndRethrow(error, context) {
  const extracted = extractError(error);
  logger.error(`Error in ${context.component}.${context.operation}`, {
    error: extracted.message,
    code: extracted.code,
    ...context.additionalInfo
  });
  if (error instanceof Error) {
    throw error;
  }
  throw new SystemError(extracted.message, ErrorCode.UNKNOWN_ERROR);
}
async function withDatabaseErrorHandling(operation, operationName) {
  try {
    return await operation();
  } catch (error) {
    const message = getErrorMessage(error);
    logger.error(`Database operation failed: ${operationName}`, {
      error: message
    });
    if (error instanceof DatabaseError) {
      throw error;
    }
    throw new DatabaseError(
      `${operationName}: ${message}`,
      ErrorCode.DB_QUERY_FAILED,
      { operation: operationName },
      error instanceof Error ? error : void 0
    );
  }
}
function withDatabaseErrorHandlingSync(operation, operationName) {
  try {
    return operation();
  } catch (error) {
    const message = getErrorMessage(error);
    logger.error(`Database operation failed: ${operationName}`, {
      error: message
    });
    if (error instanceof DatabaseError) {
      throw error;
    }
    throw new DatabaseError(
      `${operationName}: ${message}`,
      ErrorCode.DB_QUERY_FAILED,
      { operation: operationName },
      error instanceof Error ? error : void 0
    );
  }
}
function assertCondition(condition, message, code = ErrorCode.VALIDATION_FAILED) {
  if (!condition) {
    throw new StackMemoryError({
      message,
      code
    });
  }
}
function assertDefined(value, message, code = ErrorCode.NOT_FOUND) {
  if (value === null || value === void 0) {
    throw new StackMemoryError({
      message,
      code
    });
  }
}
export {
  assertCondition,
  assertDefined,
  createApiError,
  executeWithFallback,
  executeWithFallbackSync,
  extractError,
  isNetworkError,
  logAndRethrow,
  safeExecute,
  safeExecuteSync,
  toTypedError,
  withDatabaseErrorHandling,
  withDatabaseErrorHandlingSync
};
//# sourceMappingURL=error-utils.js.map
