import type {
	Author,
	CreateAuthor,
	CreateTimelineEvent,
	TimelineEvent,
	UpdateAuthor,
	UpdateTimelineEvent,
	Work,
} from "@shared/schema";
import { apiRequest } from "@/lib/queryClient";
import type { AuthorWithWorks } from "@/lib/types";

export interface AuthorSearchParams {
	limit?: number;
	offset?: number;
	search?: string;
	countryId?: string;
	language?: string;
}

/**
 * API Client for author-related operations
 * Provides type-safe methods for all author API endpoints
 */
export const authorApiClient = {
	// Author CRUD operations
	async getAuthor(authorId: string): Promise<Author> {
		return apiRequest<Author>("GET", `/api/authors/${authorId}`);
	},

	async getAuthorBySlug(slug: string): Promise<AuthorWithWorks> {
		return apiRequest<AuthorWithWorks>("GET", `/api/authors/slug/${slug}`);
	},

	async getAuthors(params?: AuthorSearchParams): Promise<Author[]> {
		const queryParams = new URLSearchParams();
		if (params?.limit) queryParams.append("limit", params.limit.toString());
		if (params?.offset) queryParams.append("offset", params.offset.toString());
		if (params?.search) queryParams.append("search", params.search);
		if (params?.countryId) queryParams.append("countryId", params.countryId);
		if (params?.language) queryParams.append("language", params.language);

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

	async createAuthor(data: CreateAuthor): Promise<Author> {
		return apiRequest<Author>("POST", "/api/authors", data);
	},

	async updateAuthor(authorId: string, data: UpdateAuthor): Promise<Author> {
		return apiRequest<Author>("PUT", `/api/authors/${authorId}`, data);
	},

	async deleteAuthor(authorId: string): Promise<void> {
		return apiRequest<void>("DELETE", `/api/authors/${authorId}`);
	},

	// Author Works operations
	async getAuthorWorks(authorId: string): Promise<Work[]> {
		return apiRequest<Work[]>("GET", `/api/authors/${authorId}/works`);
	},

	// Author Timeline operations
	async getAuthorTimeline(authorId: string): Promise<TimelineEvent[]> {
		return apiRequest<TimelineEvent[]>(
			"GET",
			`/api/authors/${authorId}/timeline`,
		);
	},

	async createTimelineEvent(
		authorId: string,
		data: CreateTimelineEvent,
	): Promise<TimelineEvent> {
		return apiRequest<TimelineEvent>(
			"POST",
			`/api/authors/${authorId}/timeline`,
			data,
		);
	},

	async updateTimelineEvent(
		eventId: string,
		data: UpdateTimelineEvent,
	): Promise<TimelineEvent> {
		return apiRequest<TimelineEvent>(
			"PUT",
			`/api/timeline-events/${eventId}`,
			data,
		);
	},

	async deleteTimelineEvent(eventId: string): Promise<void> {
		return apiRequest<void>("DELETE", `/api/timeline-events/${eventId}`);
	},

	// Search operations
	async searchAuthors(query: string): Promise<Author[]> {
		return apiRequest<Author[]>(
			"GET",
			`/api/authors/search?q=${encodeURIComponent(query)}`,
		);
	},
};
