import { ref, computed } from "vue";
import type { PropsTable } from "@/interface/index/PropsTable";

export function usePagination(
  defaultSort = "",
  fetchFunction?: () => Promise<any>
) {
  const pagination = ref<PropsTable.Pagination>({
    sortBy: defaultSort,
    descending: false,
    page: 1,
    rowsPerPage: 10,
    rowsNumber: 0,
  });

  const params = computed(() => {
    const queryParams: Record<string, string> = {
      page: pagination.value.page.toString(),
      pageSize: pagination.value.rowsPerPage.toString(),
    };

    if (pagination.value.sortBy) {
      queryParams.sortBy = pagination.value.sortBy;
      queryParams.descending = (
        pagination.value.descending ?? false
      ).toString();
    }

    return queryParams;
  });

  async function onRequest(props: PropsTable.RequestProps) {
    const newPagination = props?.pagination || props;
    if (!newPagination?.page || !newPagination?.rowsPerPage) return;

    pagination.value = { ...newPagination };
    if (
      fetchFunction &&
      pagination.value.rowsNumber &&
      pagination.value.rowsNumber > 0
    ) {
      await fetchFunction(); // เรียกฟังก์ชันที่ส่งเข้ามา
    }
  }

  async function checkAndUpdatePage(totalRows: number) {
    if (totalRows === 1 && pagination.value.page > 1) {
      pagination.value.page = pagination.value.page - 1;
    }
  }

  return {
    pagination,
    params,
    onRequest,
    checkAndUpdatePage,
  };
}
