import type {
	Collection,
	CollectionItem,
	CreateCollection,
	UpdateCollection,
} from "@shared/schema";
import { apiRequest } from "@/lib/queryClient";
import type { CollectionWithItems } from "@/lib/types";

export interface CollectionSearchParams {
	userId?: string;
	limit?: number;
	offset?: number;
	isPublic?: boolean;
}

/**
 * API Client for collection-related operations
 * Provides type-safe methods for all collection API endpoints
 */
export const collectionApiClient = {
	// Collection CRUD operations
	async getCollection(collectionId: string): Promise<CollectionWithItems> {
		return apiRequest<CollectionWithItems>(
			"GET",
			`/api/collections/${collectionId}`,
		);
	},

	async getCollectionBySlug(slug: string): Promise<CollectionWithItems> {
		return apiRequest<CollectionWithItems>(
			"GET",
			`/api/collections/slug/${slug}`,
		);
	},

	async getCollections(params?: CollectionSearchParams): Promise<Collection[]> {
		const queryParams = new URLSearchParams();
		if (params?.userId) queryParams.append("userId", params.userId);
		if (params?.limit) queryParams.append("limit", params.limit.toString());
		if (params?.offset) queryParams.append("offset", params.offset.toString());
		if (params?.isPublic !== undefined)
			queryParams.append("isPublic", params.isPublic.toString());

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

	async createCollection(data: CreateCollection): Promise<Collection> {
		return apiRequest<Collection>("POST", "/api/collections", data);
	},

	async updateCollection(
		collectionId: string,
		data: UpdateCollection,
	): Promise<Collection> {
		return apiRequest<Collection>(
			"PUT",
			`/api/collections/${collectionId}`,
			data,
		);
	},

	async deleteCollection(collectionId: string): Promise<void> {
		return apiRequest<void>("DELETE", `/api/collections/${collectionId}`);
	},

	// Collection Items operations
	async addWorkToCollection(
		collectionId: string,
		workId: string,
		order?: number,
	): Promise<CollectionItem> {
		return apiRequest<CollectionItem>(
			"POST",
			`/api/collections/${collectionId}/items`,
			{ workId, order },
		);
	},

	async removeWorkFromCollection(
		collectionId: string,
		workId: string,
	): Promise<void> {
		return apiRequest<void>(
			"DELETE",
			`/api/collections/${collectionId}/items/${workId}`,
		);
	},

	async reorderCollectionItems(
		collectionId: string,
		items: { id: string; order: number }[],
	): Promise<CollectionItem[]> {
		return apiRequest<CollectionItem[]>(
			"PUT",
			`/api/collections/${collectionId}/reorder`,
			{ items },
		);
	},

	// User Collections operations
	async getUserCollections(userId: string): Promise<Collection[]> {
		return apiRequest<Collection[]>("GET", `/api/users/${userId}/collections`);
	},
};
