import { computed, ref } from "vue";
import type { ApiPagination } from "@/core/types/api";

function createDefaultPagination(
  overrides?: Partial<ApiPagination>
): ApiPagination {
  return {
    current_page: 1,
    per_page: 10,
    total: 0,
    last_page: 1,
    from: null,
    to: null,
    has_more_pages: false,
    ...overrides,
  };
}

export function useApiPagination(initial?: Partial<ApiPagination>) {
  const pagination = ref<ApiPagination>(createDefaultPagination(initial));

  const tablePagination = computed(() => ({
    pageIndex: pagination.value.current_page - 1,
    pageSize: pagination.value.per_page,
  }));

  function applyPagination(meta: ApiPagination) {
    pagination.value = meta;
  }

  function getRangeLabel() {
    const { from, to, total } = pagination.value;

    if (!total) {
      return "No results";
    }

    if (from == null || to == null) {
      return `${total} row(s)`;
    }

    return `Showing ${from} to ${to} of ${total}`;
  }

  return {
    pagination,
    tablePagination,
    applyPagination,
    getRangeLabel,
  };
}
