import type { InfiniteData } from "@tanstack/react-query";
import type { GetTasksByTaskPhaseResponse, TaskItemType } from "../task/types/TaskTypes";

export type TasksByTaskPhaseInfiniteData = InfiniteData<GetTasksByTaskPhaseResponse, string | undefined>;

export const getTaskPhaseItems = (data?: TasksByTaskPhaseInfiniteData): TaskItemType[] =>
  data?.pages.flatMap((page) => page.data?.items ?? []) ?? [];

const redistributeItemsAcrossPages = (
  pages: GetTasksByTaskPhaseResponse[],
  items: TaskItemType[],
): GetTasksByTaskPhaseResponse[] => {
  let offset = 0;

  return pages.map((page) => {
    const pageSize = page.data?.items.length ?? 0;
    const pageItems = items.slice(offset, offset + pageSize);
    offset += pageSize;

    return {
      ...page,
      data: {
        ...page.data,
        items: pageItems,
      },
    };
  });
};

export const updateTaskPhaseItems = (
  current: TasksByTaskPhaseInfiniteData | undefined,
  updater: (items: TaskItemType[]) => TaskItemType[],
): TasksByTaskPhaseInfiniteData | undefined => {
  if (!current?.pages.length) return current;

  const updatedItems = updater(getTaskPhaseItems(current));

  return {
    ...current,
    pages: redistributeItemsAcrossPages(current.pages, updatedItems),
  };
};

export const insertTaskPhaseItem = (
  current: TasksByTaskPhaseInfiniteData | undefined,
  item: TaskItemType,
  index: number,
): TasksByTaskPhaseInfiniteData => {
  const items = getTaskPhaseItems(current);
  const nextItems = [...items];
  nextItems.splice(index, 0, item);

  if (!current?.pages.length) {
    return {
      pages: [
        {
          status: 200,
          success: true,
          statusCode: 200,
          data: {
            items: nextItems,
            pager: {
              limit: 10,
              nextCursor: null,
              previousCursor: null,
              hasNextPage: false,
              hasPreviousPage: false,
            },
          },
        },
      ],
      pageParams: [undefined],
    };
  }

  return {
    ...current,
    pages: redistributeItemsAcrossPages(current.pages, nextItems),
  };
};
