// #region TranslateJobsApi [C:2] [TYPE Module] [SEMANTICS translate, jobs, api, crud]
// @BRIEF API client for translation job CRUD — list, create, update, delete, duplicate.
// @LAYER API
// @RELATION DEPENDS_ON -> [ApiModule]
// @POST All functions return typed responses or throw normalized TranslateApiError.

import { api } from '$lib/api';

export interface TranslateApiError {
	message: string;
	code: 'TRANSLATE_API_ERROR';
	retryable: boolean;
}

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 JobQueryOptions {
	page?: number;
	page_size?: number;
	status?: string;
}

// #region fetchJobs [C:2] [TYPE Function] [SEMANTICS translate, jobs, list]
// @BRIEF Fetch paginated list of translation jobs.
// @PRE options may contain page/page_size/status filters.
// @POST Returns paginated job list response.
// @RELATION DEPENDS_ON -> [ApiModule.fetchApi]
export async function fetchJobs<T = unknown>(options: JobQueryOptions = {}): 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));
		if (options.status) params.append('status', options.status);
		const query = params.toString();
		return await api.fetchApi<T>(`/translate/jobs${query ? `?${query}` : ''}`);
	} catch (error) {
		throw normalizeTranslateError(error, 'Failed to load translation jobs');
	}
}
// #endregion fetchJobs

// #region createJob [C:2] [TYPE Function] [SEMANTICS translate, jobs, create]
// @BRIEF Create a new translation job.
// @PRE payload contains valid job configuration.
// @POST Returns created job response.
// @SIDE_EFFECT Creates a new translation job on the backend.
// @RELATION DEPENDS_ON -> [ApiModule.postApi]
export async function createJob<T = unknown>(payload: Record<string, unknown>): Promise<T> {
	try {
		return await api.postApi<T>('/translate/jobs', payload);
	} catch (error) {
		throw normalizeTranslateError(error, 'Failed to create translation job');
	}
}
// #endregion createJob

// #region updateJob [C:2] [TYPE Function] [SEMANTICS translate, jobs, update]
// @BRIEF Update an existing translation job.
// @PRE jobId is a non-empty string. payload contains fields to update.
// @POST Returns updated job response.
// @SIDE_EFFECT Modifies the job on the backend.
// @RELATION DEPENDS_ON -> [ApiModule.requestApi]
export async function updateJob<T = unknown>(jobId: string, payload: Record<string, unknown>): Promise<T> {
	try {
		return await api.requestApi<T>(`/translate/jobs/${jobId}`, 'PUT', payload);
	} catch (error) {
		throw normalizeTranslateError(error, 'Failed to update translation job');
	}
}
// #endregion updateJob

// #region deleteJob [C:2] [TYPE Function] [SEMANTICS translate, jobs, delete]
// @BRIEF Delete a translation job.
// @PRE jobId is a non-empty string.
// @POST Returns success response.
// @SIDE_EFFECT Removes the job and associated runs from the backend.
// @RELATION DEPENDS_ON -> [ApiModule.deleteApi]
export async function deleteJob<T = unknown>(jobId: string): Promise<T> {
	try {
		return await api.deleteApi<T>(`/translate/jobs/${jobId}`);
	} catch (error) {
		throw normalizeTranslateError(error, 'Failed to delete translation job');
	}
}
// #endregion deleteJob

// #region duplicateJob [C:2] [TYPE Function] [SEMANTICS translate, jobs, duplicate]
// @BRIEF Duplicate a translation job (deep copy including configuration).
// @PRE jobId is a non-empty string.
// @POST Returns duplicated job response.
// @SIDE_EFFECT Creates a new job as a copy of the specified one.
// @RELATION DEPENDS_ON -> [ApiModule.postApi]
export async function duplicateJob<T = unknown>(jobId: string): Promise<T> {
	try {
		return await api.postApi<T>(`/translate/jobs/${jobId}/duplicate`, {});
	} catch (error) {
		throw normalizeTranslateError(error, 'Failed to duplicate translation job');
	}
}
// #endregion duplicateJob
// #endregion TranslateJobsApi
