import axios from 'axios';
import {
  BaseApiResponse,
  ErrorApiResponse,
  SuccessApiResponse,
} from '@/types/api/api-general';

export const isResponseSuccess = <T>(
  res?: BaseApiResponse<T>
): res is SuccessApiResponse<T> => {
  return res?.status === 'success';
};

export const isResponseError = <T>(
  res?: BaseApiResponse<T>
): res is ErrorApiResponse => {
  return res?.status === 'error';
};

export const getErrorMessage = async (
  error: unknown,
  fallbackMessage: string
) => {
  if (axios.isAxiosError(error)) {
    const responseData = error.response?.data;

    if (responseData instanceof Blob) {
      try {
        const parsed = JSON.parse(await responseData.text()) as {
          message?: string;
        };
        return parsed.message || fallbackMessage;
      } catch {
        return fallbackMessage;
      }
    }

    if (
      responseData &&
      typeof responseData === 'object' &&
      'message' in responseData &&
      typeof responseData.message === 'string'
    ) {
      return responseData.message;
    }

    return error.message || fallbackMessage;
  }

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

  return fallbackMessage;
};
