// Custom bookmarks for PDF pages (saved in database)
// Procedural implementation (no OOP)

interface MediaBookmark {
  id: string;
  mediaItemId: string;
  userId: string;
  pageNumber: number;
  title: string;
  createdAt: string;
}

interface MediaBookmarksState {
  mediaItemId: string;
  bookmarks: MediaBookmark[];
}

function createMediaBookmarks(mediaItemId: string): MediaBookmarksState {
  return {
    mediaItemId,
    bookmarks: [],
  };
}

async function loadMediaBookmarks(
  state: MediaBookmarksState,
): Promise<MediaBookmarksState> {
  try {
    const response = await fetch(
      `/api/media-items/${state.mediaItemId}/bookmarks`,
    );
    if (!response.ok) throw new Error("Failed to load bookmarks");

    const data = await response.json();
    return { ...state, bookmarks: data.bookmarks || [] };
  } catch (error) {
    console.error("Failed to load bookmarks:", error);
    return { ...state, bookmarks: [] };
  }
}

async function addMediaBookmark(
  state: MediaBookmarksState,
  pageNumber: number,
  title?: string,
): Promise<MediaBookmarksState & { bookmark: MediaBookmark }> {
  const bookmark: MediaBookmark = {
    id: crypto.randomUUID(),
    mediaItemId: state.mediaItemId,
    userId: "",
    pageNumber,
    title: title || `Page ${pageNumber}`,
    createdAt: new Date().toISOString(),
  };

  try {
    const response = await fetch(
      `/api/media-items/${state.mediaItemId}/bookmarks`,
      {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          page_number: pageNumber,
          title: bookmark.title,
          position: `pdf:page:${pageNumber}`,
        }),
      },
    );

    if (!response.ok) throw new Error("Failed to create bookmark");

    const created = await response.json();

    return {
      ...state,
      bookmarks: [...state.bookmarks, created],
      bookmark: created,
    };
  } catch (error) {
    console.error("Failed to add bookmark:", error);
    throw error;
  }
}

async function removeMediaBookmark(
  state: MediaBookmarksState,
  bookmarkId: string,
): Promise<MediaBookmarksState> {
  try {
    const response = await fetch(
      `/api/media-items/${state.mediaItemId}/bookmarks/${bookmarkId}`,
      {
        method: "DELETE",
      },
    );

    if (!response.ok) throw new Error("Failed to remove bookmark");

    return {
      ...state,
      bookmarks: state.bookmarks.filter((b) => b.id !== bookmarkId),
    };
  } catch (error) {
    console.error("Failed to remove bookmark:", error);
    throw error;
  }
}

function getMediaBookmarks(state: MediaBookmarksState): MediaBookmark[] {
  return [...state.bookmarks].sort((a, b) => a.pageNumber - b.pageNumber);
}

function hasMediaBookmarkAt(
  state: MediaBookmarksState,
  pageNumber: number,
): boolean {
  return state.bookmarks.some((b) => b.pageNumber === pageNumber);
}

function getMediaBookmarkAt(
  state: MediaBookmarksState,
  pageNumber: number,
): MediaBookmark | null {
  return state.bookmarks.find((b) => b.pageNumber === pageNumber) || null;
}
