import type { ApiIdentifier, PaginatedResponse } from "@/types/api";

export function getEntityId(entity?: ApiIdentifier | null) {
  if (!entity) return "";
  return entity._id ?? entity.id ?? "";
}

export function getItems<T>(payload: PaginatedResponse<T> | T[] | undefined | null) {
  if (!payload) return [] as T[];
  if (Array.isArray(payload)) return payload;
  if (Array.isArray(payload.items)) return payload.items;
  if (Array.isArray(payload.data)) return payload.data;
  return [] as T[];
}

export function getTotal<T>(payload: PaginatedResponse<T> | undefined | null) {
  if (!payload) return 0;
  if (typeof payload.pagination?.total === "number") return payload.pagination.total;
  if (typeof payload.total === "number") return payload.total;
  return getItems(payload).length;
}

export function getPagination<T>(payload: PaginatedResponse<T> | undefined | null) {
  return payload?.pagination ?? null;
}

export function toQueryString(params: Record<string, string | number | boolean | null | undefined>) {
  const search = new URLSearchParams();

  Object.entries(params).forEach(([key, value]) => {
    if (value === undefined || value === null || value === "") return;
    search.set(key, String(value));
  });

  return search.toString();
}
