import type { CreateTag, Tag, UpdateTag, Work } from "@shared/schema";
import { apiRequest } from "@/lib/queryClient";

export interface TagSearchParams {
	type?: string;
	limit?: number;
	offset?: number;
	search?: string;
}

/**
 * API Client for tag-related operations
 * Provides type-safe methods for all tag API endpoints
 */
export const tagApiClient = {
	// Tag CRUD operations
	async getTag(tagId: string): Promise<Tag> {
		return apiRequest<Tag>("GET", `/api/tags/${tagId}`);
	},

	async getTagByName(name: string): Promise<Tag> {
		return apiRequest<Tag>("GET", `/api/tags/name/${encodeURIComponent(name)}`);
	},

	async getTags(params?: TagSearchParams): Promise<Tag[]> {
		const queryParams = new URLSearchParams();
		if (params?.type) queryParams.append("type", params.type);
		if (params?.search) queryParams.append("search", params.search);
		if (params?.limit) queryParams.append("limit", params.limit.toString());
		if (params?.offset) queryParams.append("offset", params.offset.toString());

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

	async createTag(data: CreateTag): Promise<Tag> {
		return apiRequest<Tag>("POST", "/api/tags", data);
	},

	async updateTag(tagId: string, data: UpdateTag): Promise<Tag> {
		return apiRequest<Tag>("PUT", `/api/tags/${tagId}`, data);
	},

	async deleteTag(tagId: string): Promise<void> {
		return apiRequest<void>("DELETE", `/api/tags/${tagId}`);
	},

	// Tag Works operations
	async getTagWorks(tagId: string): Promise<Work[]> {
		return apiRequest<Work[]>("GET", `/api/tags/${tagId}/works`);
	},

	async getWorksByTagName(tagName: string): Promise<Work[]> {
		return apiRequest<Work[]>(
			"GET",
			`/api/tags/name/${encodeURIComponent(tagName)}/works`,
		);
	},

	// Tag Management
	async getPopularTags(limit = 20): Promise<Tag[]> {
		return apiRequest<Tag[]>("GET", `/api/tags/popular?limit=${limit}`);
	},

	async getTagsByType(type: string): Promise<Tag[]> {
		return apiRequest<Tag[]>("GET", `/api/tags/type/${type}`);
	},

	async searchTags(query: string): Promise<Tag[]> {
		return apiRequest<Tag[]>(
			"GET",
			`/api/tags/search?q=${encodeURIComponent(query)}`,
		);
	},

	// Work Tags operations
	async addTagToWork(workId: string, tagId: string): Promise<void> {
		return apiRequest<void>("POST", `/api/works/${workId}/tags`, { tagId });
	},

	async removeTagFromWork(workId: string, tagId: string): Promise<void> {
		return apiRequest<void>("DELETE", `/api/works/${workId}/tags/${tagId}`);
	},

	async getWorkTags(workId: string): Promise<Tag[]> {
		return apiRequest<Tag[]>("GET", `/api/works/${workId}/tags`);
	},
};
