import { ApiError, AuthExpiredError } from '@/shared/api/httpClient';

export const DEFAULT_ERROR_MESSAGE = 'Request failed';
export const AUTH_EXPIRED_ERROR_MESSAGE = 'Please sign in again.';
export const FORBIDDEN_ERROR_MESSAGE =
  "You don't have permission to do that.";

/** True for a backend 403 (authenticated but not permitted). */
export function isForbiddenError(error: unknown): boolean {
  return error instanceof ApiError && error.status === 403;
}

export function getErrorMessage(error: unknown, fallbackMessage = DEFAULT_ERROR_MESSAGE): string {
  if (error instanceof AuthExpiredError) {
    return AUTH_EXPIRED_ERROR_MESSAGE;
  }

  if (error instanceof ApiError) {
    return error.message || fallbackMessage;
  }

  if (error instanceof Error) {
    return error.message || fallbackMessage;
  }

  return fallbackMessage;
}

export function getOptionalErrorMessage(error: unknown, fallbackMessage = DEFAULT_ERROR_MESSAGE): string | null {
  return error ? getErrorMessage(error, fallbackMessage) : null;
}
