// #region TranslateDictionariesApi [C:3] [TYPE Module] [SEMANTICS translate, dictionaries, api, crud, entries]
// @BRIEF API client for translation dictionary CRUD — list, create, update, delete, entries, import.
// @LAYER API
// @RELATION DEPENDS_ON -> [ApiModule]
// @POST All methods return typed responses or throw normalized TranslateApiError.

import { api } from '$lib/api';
import type { TranslateApiError } from './jobs';

function normalizeTranslateError(error: unknown, defaultMessage: string = 'Translation API error'): TranslateApiError {
	const message =
		(error && typeof (error as Error).message === 'string' && (error as Error).message) ||
		(typeof error === 'string' && error) ||
		defaultMessage;
	return { message, code: 'TRANSLATE_API_ERROR' as const, retryable: true };
}

export interface PaginationOptions {
	page?: number;
	page_size?: number;
}

// #region dictionaryApi [C:3] [TYPE Block] [SEMANTICS translate, dictionaries, api, crud]
// @BRIEF Dictionary CRUD operations — each method wraps api.* with error normalization.
// @RELATION DEPENDS_ON -> [ApiModule.fetchApi]
// @RELATION DEPENDS_ON -> [ApiModule.postApi]
// @RELATION DEPENDS_ON -> [ApiModule.requestApi]
// @RELATION DEPENDS_ON -> [ApiModule.deleteApi]
export const dictionaryApi = {
	// #region fetchDictionaries [C:2] [TYPE Function] [SEMANTICS translate, dictionaries, list]
	async fetchDictionaries<T = unknown>(options: PaginationOptions = {}): Promise<T> {
		try {
			const params = new URLSearchParams();
			if (options.page != null) params.append('page', String(options.page));
			if (options.page_size != null) params.append('page_size', String(options.page_size));
			const query = params.toString();
			return await api.fetchApi<T>(`/translate/dictionaries${query ? `?${query}` : ''}`);
		} catch (error) {
			throw normalizeTranslateError(error, 'Failed to load dictionaries');
		}
	},
	// #endregion fetchDictionaries

	// #region createDictionary [C:2] [TYPE Function] [SEMANTICS translate, dictionaries, create]
	async createDictionary<T = unknown>(payload: Record<string, unknown>): Promise<T> {
		try {
			return await api.postApi<T>('/translate/dictionaries', payload);
		} catch (error) {
			throw normalizeTranslateError(error, 'Failed to create dictionary');
		}
	},
	// #endregion createDictionary

	// #region getDictionary [C:2] [TYPE Function] [SEMANTICS translate, dictionaries, get]
	async getDictionary<T = unknown>(dictionaryId: string): Promise<T> {
		try {
			return await api.fetchApi<T>(`/translate/dictionaries/${dictionaryId}`);
		} catch (error) {
			throw normalizeTranslateError(error, 'Failed to load dictionary');
		}
	},
	// #endregion getDictionary

	// #region updateDictionary [C:2] [TYPE Function] [SEMANTICS translate, dictionaries, update]
	async updateDictionary<T = unknown>(dictionaryId: string, payload: Record<string, unknown>): Promise<T> {
		try {
			return await api.requestApi<T>(`/translate/dictionaries/${dictionaryId}`, 'PUT', payload);
		} catch (error) {
			throw normalizeTranslateError(error, 'Failed to update dictionary');
		}
	},
	// #endregion updateDictionary

	// #region deleteDictionary [C:2] [TYPE Function] [SEMANTICS translate, dictionaries, delete]
	async deleteDictionary<T = unknown>(dictionaryId: string): Promise<T> {
		try {
			return await api.deleteApi<T>(`/translate/dictionaries/${dictionaryId}`);
		} catch (error) {
			throw normalizeTranslateError(error, 'Failed to delete dictionary');
		}
	},
	// #endregion deleteDictionary

	// #region fetchEntries [C:2] [TYPE Function] [SEMANTICS translate, dictionaries, entries, list]
	async fetchEntries<T = unknown>(dictionaryId: string, options: PaginationOptions = {}): Promise<T> {
		try {
			const params = new URLSearchParams();
			if (options.page != null) params.append('page', String(options.page));
			if (options.page_size != null) params.append('page_size', String(options.page_size));
			const query = params.toString();
			return await api.fetchApi<T>(
				`/translate/dictionaries/${dictionaryId}/entries${query ? `?${query}` : ''}`
			);
		} catch (error) {
			throw normalizeTranslateError(error, 'Failed to load dictionary entries');
		}
	},
	// #endregion fetchEntries

	// #region createEntry [C:2] [TYPE Function] [SEMANTICS translate, dictionaries, entries, create]
	async createEntry<T = unknown>(dictionaryId: string, payload: Record<string, unknown>): Promise<T> {
		try {
			return await api.postApi<T>(`/translate/dictionaries/${dictionaryId}/entries`, payload);
		} catch (error) {
			throw normalizeTranslateError(error, 'Failed to create dictionary entry');
		}
	},
	// #endregion createEntry

	// #region updateEntry [C:2] [TYPE Function] [SEMANTICS translate, dictionaries, entries, update]
	async updateEntry<T = unknown>(dictionaryId: string, entryId: string, payload: Record<string, unknown>): Promise<T> {
		try {
			return await api.requestApi<T>(
				`/translate/dictionaries/${dictionaryId}/entries/${entryId}`,
				'PUT',
				payload
			);
		} catch (error) {
			throw normalizeTranslateError(error, 'Failed to update dictionary entry');
		}
	},
	// #endregion updateEntry

	// #region deleteEntry [C:2] [TYPE Function] [SEMANTICS translate, dictionaries, entries, delete]
	async deleteEntry<T = unknown>(dictionaryId: string, entryId: string): Promise<T> {
		try {
			return await api.deleteApi<T>(`/translate/dictionaries/${dictionaryId}/entries/${entryId}`);
		} catch (error) {
			throw normalizeTranslateError(error, 'Failed to delete dictionary entry');
		}
	},
	// #endregion deleteEntry

	// #region importEntries [C:2] [TYPE Function] [SEMANTICS translate, dictionaries, entries, import]
	async importEntries<T = unknown>(dictionaryId: string, payload: Record<string, unknown>): Promise<T> {
		try {
			return await api.postApi<T>(`/translate/dictionaries/${dictionaryId}/import`, payload);
		} catch (error) {
			throw normalizeTranslateError(error, 'Failed to import dictionary entries');
		}
	},
	// #endregion importEntries
};
// #endregion dictionaryApi
// #endregion TranslateDictionariesApi
