import { apiPut } from "../../api";

interface ReadingProgress {
  current_page: number;
  total_pages: number;
}

export async function updateReadingProgress(
  mediaItemId: string,
  progress: ReadingProgress,
): Promise<void> {
  const response = await apiPut(
    `/media-items/${mediaItemId}/progress`,
    progress,
  );
  await response.json();
}

export function getChapterNavigation(chapters: any[]) {
  return {
    getNextChapter: (currentPage: number) => {
      for (let i = 0; i < chapters.length - 1; i++) {
        const chapter = chapters[i];
        const nextChapter = chapters[i + 1];

        if (
          currentPage >= chapter.start_page &&
          currentPage < nextChapter.start_page
        ) {
          return nextChapter.start_page;
        }
      }
      return null;
    },

    getPreviousChapter: (currentPage: number) => {
      for (let i = 1; i < chapters.length; i++) {
        const chapter = chapters[i];

        if (
          currentPage >= chapter.start_page &&
          currentPage < chapter.start_page + chapter.page_count
        ) {
          return chapters[i - 1].start_page;
        }
      }

      if (currentPage < chapters[0].start_page) {
        return null;
      }

      return chapters[0].start_page;
    },
  };
}
