interface IDanakError {
  status?: number;
  statusCode?: number;
  success?: boolean;
  error?: string | { message?: string[] | string };
  message?: string[] | string;
}

const resolveMessage = (
  messages: string[] | string | undefined
): string | null => {
  if (Array.isArray(messages) && messages.length > 0) {
    return messages[0];
  }
  if (typeof messages === "string" && messages.trim().length > 0) {
    return messages;
  }
  return null;
};

export const extractErrorMessage = (
  error: Error | unknown,
  fallbackMessage: string = "خطایی رخ داده است"
): string => {
  try {
    const axiosError = error as { response?: { data?: IDanakError } };
    const data = axiosError?.response?.data;

    if (!data) {
      return fallbackMessage;
    }

    const directMessage = resolveMessage(data.message);
    if (directMessage) {
      return directMessage;
    }

    if (typeof data.error === "object" && data.error !== null) {
      const nestedMessage = resolveMessage(data.error.message);
      if (nestedMessage) {
        return nestedMessage;
      }
    }

    if (typeof data.error === "string" && data.error.trim().length > 0) {
      return data.error;
    }

    return fallbackMessage;
  } catch {
    return fallbackMessage;
  }
};
