export function normalizePage(data, mapItem = normalizeRecord) {
  const source = asRecord(data);
  const rawItems = Array.isArray(data)
    ? data
    : arrayValue(source.items, source.agencies, source.list, source.records, source.content, source.rows);
  const page = positiveNumber(source.page ?? source.page_no ?? source.pageNo, 1);
  const pageSize = positiveNumber(source.pageSize ?? source.page_size ?? source.size, rawItems.length || 20);

  return {
    items: rawItems.map((item) => mapItem(asRecord(item))),
    page,
    pageSize,
    total: nonNegativeNumber(source.total ?? source.total_count ?? source.totalCount, rawItems.length)
  };
}

export function normalizeRecord(value) {
  return asRecord(value);
}

export function asRecord(value) {
  return value && typeof value === "object" && !Array.isArray(value) ? value : {};
}

export function arrayValue(...values) {
  return values.find(Array.isArray) || [];
}

export function textValue(...values) {
  const value = values.find((item) => item !== undefined && item !== null && item !== "");
  return value === undefined ? "" : String(value);
}

export function numberValue(value, fallback = 0) {
  const parsed = Number(value);
  return Number.isFinite(parsed) ? parsed : fallback;
}

export function booleanValue(...values) {
  const value = values.find((item) => item !== undefined && item !== null);
  if (typeof value === "string") {
    return ["1", "true", "enabled", "active", "yes"].includes(value.toLowerCase());
  }
  return Boolean(value);
}

export function entityId(item) {
  return textValue(item.id, item.userId, item.user_id, item.roomId, item.room_id, item.resourceId, item.resource_id);
}

function positiveNumber(value, fallback) {
  const parsed = Number(value);
  return Number.isFinite(parsed) && parsed > 0 ? parsed : fallback;
}

function nonNegativeNumber(value, fallback) {
  const parsed = Number(value);
  return Number.isFinite(parsed) && parsed >= 0 ? parsed : fallback;
}
