/** biome-ignore-all lint/suspicious/noExplicitAny: <intended> */
import type { Table } from "@tanstack/react-table";
import type { RefObject } from "react";

export type onMutate = () => {
	pageIdx: number | undefined;
};

export type onSettled = (
	_a: any,
	_b: any,
	_c: any,
	context?: { pageIdx?: number },
) => void;

export const MutationPageRestore = (
	tableRef: RefObject<Table<any> | null>,
): { onMutate: onMutate; onSettled: onSettled } => {
	return {
		onMutate: () => {
			const pageIdx = tableRef.current?.getState().pagination.pageIndex; // 0 based index
			return {
				pageIdx: pageIdx === 0 ? undefined : pageIdx, // solo una pagina
			};
		},
		onSettled: (_a: any, _b: any, _c: any, context?: { pageIdx?: number }) => {
			// wait a tick to ensure the table has the latest data after invalidation
			setTimeout(() => {
				if (context?.pageIdx !== undefined) {
					const pageCount = tableRef.current?.getPageCount() || 0;
					// if the page index from context is greater than the current page count, set it to the last page
					if (context.pageIdx >= pageCount) {
						tableRef.current?.setPageIndex(pageCount - 1);
					} else {
						tableRef.current?.setPageIndex(context.pageIdx);
					}
				}
			}, 0);
		},
	};
};
