import type { Bookmark, CreateBookmark, UpdateBookmark } from "@shared/schema";
import { apiRequest } from "@/lib/queryClient";
import type { BookmarkWithWork } from "@/lib/types";

export interface BookmarkSearchParams {
	userId?: string;
	workId?: string;
	limit?: number;
	offset?: number;
}

/**
 * API Client for bookmark-related operations
 * Provides type-safe methods for all bookmark API endpoints
 */
export const bookmarkApiClient = {
	// Bookmark CRUD operations
	async getBookmark(bookmarkId: string): Promise<BookmarkWithWork> {
		return apiRequest<BookmarkWithWork>("GET", `/api/bookmarks/${bookmarkId}`);
	},

	async getBookmarks(
		params?: BookmarkSearchParams,
	): Promise<BookmarkWithWork[]> {
		const queryParams = new URLSearchParams();
		if (params?.userId) queryParams.append("userId", params.userId);
		if (params?.workId) queryParams.append("workId", params.workId);
		if (params?.limit) queryParams.append("limit", params.limit.toString());
		if (params?.offset) queryParams.append("offset", params.offset.toString());

		return apiRequest<BookmarkWithWork[]>(
			"GET",
			`/api/bookmarks?${queryParams.toString()}`,
		);
	},

	async createBookmark(data: CreateBookmark): Promise<Bookmark> {
		return apiRequest<Bookmark>("POST", "/api/bookmarks", data);
	},

	async updateBookmark(
		bookmarkId: string,
		data: UpdateBookmark,
	): Promise<Bookmark> {
		return apiRequest<Bookmark>("PUT", `/api/bookmarks/${bookmarkId}`, data);
	},

	async deleteBookmark(bookmarkId: string): Promise<void> {
		return apiRequest<void>("DELETE", `/api/bookmarks/${bookmarkId}`);
	},

	// User Bookmarks operations
	async getUserBookmarks(userId: string): Promise<BookmarkWithWork[]> {
		return apiRequest<BookmarkWithWork[]>(
			"GET",
			`/api/users/${userId}/bookmarks`,
		);
	},

	async bookmarkWork(
		userId: string,
		workId: string,
		note?: string,
	): Promise<Bookmark> {
		return apiRequest<Bookmark>("POST", "/api/bookmarks", {
			userId,
			workId,
			note,
		});
	},

	async unbookmarkWork(userId: string, workId: string): Promise<void> {
		return apiRequest<void>(
			"DELETE",
			`/api/bookmarks/user/${userId}/work/${workId}`,
		);
	},

	async isWorkBookmarked(userId: string, workId: string): Promise<boolean> {
		try {
			await apiRequest("GET", `/api/bookmarks/user/${userId}/work/${workId}`);
			return true;
		} catch {
			return false;
		}
	},
};
