import axios from 'axios';

export interface ApiErrorBody {
  code: number;
  error: string;
  message: string;
}

export const CODE_TOTP_REQUIRED = 42801;

export function getApiErrorMessage(
  error: unknown,
  fallback = 'An error occurred',
): string {
  if (axios.isAxiosError(error)) {
    const body = error.response?.data as Partial<ApiErrorBody> | undefined;
    if (body?.message) return body.message;
    return error.message || fallback;
  }
  if (error instanceof Error) return error.message;
  return fallback;
}

export function isTotpRequiredError(error: unknown): boolean {
  return (
    axios.isAxiosError(error) &&
    (error.response?.data as Partial<ApiErrorBody> | undefined)?.code ===
      CODE_TOTP_REQUIRED
  );
}

export function getApiErrorCode(error: unknown): number | undefined {
  if (axios.isAxiosError(error)) {
    return (error.response?.data as Partial<ApiErrorBody> | undefined)?.code;
  }
  return undefined;
}

/**
 * Unwrap an API response that has the shape { code, message, data?: T }.
 * Falls back to null if the response or data is missing.
 */
export function unwrapData<T>(resp: { data?: { data?: T } } | undefined): T | null {
  return resp?.data?.data ?? null;
}
