type LaravelErrorBody = {
  message?: string;
  errors?: Record<string, string[]>;
  error?: {
    message?: string;
  };
};

export function extractApiErrorMessage(data: unknown, fallback?: string): string | undefined {
  if (typeof data !== 'object' || data === null) {
    return fallback;
  }

  const body = data as LaravelErrorBody;

  if (typeof body.message === 'string' && body.message !== '') {
    return body.message;
  }

  if (typeof body.error?.message === 'string' && body.error.message !== '') {
    return body.error.message;
  }

  if (body.errors) {
    const first = Object.values(body.errors).flat()[0];
    if (typeof first === 'string' && first !== '') {
      return first;
    }
  }

  return fallback;
}

type ApiErrorContext = {
  blockers?: Array<{ id: string; ticket_number: string; subject: string }>;
  requires_override?: boolean;
  mode?: string;
};

export function extractApiErrorContext(data: unknown): ApiErrorContext | undefined {
  if (typeof data !== 'object' || data === null) {
    return undefined;
  }
  const body = data as { error?: { context?: ApiErrorContext } };
  return body.error?.context;
}

export function isAxiosErrorWithResponse(
  error: unknown,
): error is { response: { data: unknown; status?: number } } {
  return (
    typeof error === 'object' &&
    error !== null &&
    'response' in error &&
    typeof (error as { response?: unknown }).response === 'object' &&
    (error as { response: { data?: unknown } }).response !== null
  );
}
