import type { PaginatedResponse } from "@/types";

/** Odoo list endpoints return `{ data: T[], total, page, size }`; SPA types use `items`. */
export function asPaginated<T>(raw: unknown): PaginatedResponse<T> {
  const r = raw as {
    data?: T[];
    items?: T[];
    total?: number;
    page?: number;
    size?: number;
  };
  const items = r.items ?? r.data ?? [];
  const total = r.total ?? items.length;
  const page = r.page ?? 1;
  const size = r.size ?? (items.length || 20);
  const pages = size > 0 ? Math.max(1, Math.ceil(total / size)) : 1;
  return { items, total, page, size, pages };
}

/** Single-record wrappers: `{ data: T }` or bare `T`. */
export function asRecordData<T>(raw: unknown): T {
  if (raw && typeof raw === "object" && "data" in raw && (raw as { data: unknown }).data !== undefined) {
    return (raw as { data: T }).data;
  }
  return raw as T;
}
