// #region TranslateDatasourcesApi [C:2] [TYPE Module] [SEMANTICS translate, datasources, columns, preview, api]
// @BRIEF API client for translation datasources — column fetching, preview, row-level review actions.
// @LAYER API
// @RELATION DEPENDS_ON -> [ApiModule]
// @POST All functions 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 };
}

// #region fetchDatasources [C:2] [TYPE Function] [SEMANTICS translate, datasources, list]
// @BRIEF Fetch available datasources for a given environment.
// @PRE envId is a non-empty string.
// @POST Returns list of datasources matching the search.
// @RELATION DEPENDS_ON -> [ApiModule.fetchApi]
export async function fetchDatasources<T = unknown>(envId: string, search: string = ''): Promise<T> {
	try {
		return await api.fetchApi<T>(
			`/translate/datasources?env_id=${encodeURIComponent(envId)}&search=${encodeURIComponent(search)}`
		);
	} catch (error) {
		throw normalizeTranslateError(error, 'Failed to fetch datasources');
	}
}
// #endregion fetchDatasources

// #region fetchDatasourceColumns [C:2] [TYPE Function] [SEMANTICS translate, datasources, columns]
// @BRIEF Fetch columns for a specific datasource.
// @PRE datasourceId and envId are non-empty strings.
// @POST Returns list of column definitions.
// @RELATION DEPENDS_ON -> [ApiModule.fetchApi]
export async function fetchDatasourceColumns<T = unknown>(datasourceId: string, envId: string): Promise<T> {
	try {
		return await api.fetchApi<T>(
			`/translate/datasources/${datasourceId}/columns?env_id=${encodeURIComponent(envId)}`
		);
	} catch (error) {
		throw normalizeTranslateError(error, 'Failed to fetch datasource columns');
	}
}
// #endregion fetchDatasourceColumns

// #region fetchPreview [C:2] [TYPE Function] [SEMANTICS translate, preview, rows]
// @BRIEF Fetch a sample preview of rows for a translation job.
// @PRE jobId is a non-empty string.
// @POST Returns preview data with sample rows.
// @RELATION DEPENDS_ON -> [ApiModule.postApi]
export async function fetchPreview<T = unknown>(jobId: string, sampleSize: number = 10, envId: string = ''): Promise<T> {
	try {
		const body: Record<string, unknown> = { sample_size: sampleSize };
		if (envId) body.env_id = envId;
		return await api.postApi<T>(`/translate/jobs/${jobId}/preview`, body);
	} catch (error) {
		throw normalizeTranslateError(error, 'Failed to run preview');
	}
}
// #endregion fetchPreview

// #region approveRow [C:2] [TYPE Function] [SEMANTICS translate, preview, approve, row]
// @BRIEF Approve a specific preview row for translation.
// @PRE jobId and rowKey are non-empty strings.
// @POST Row is approved for translation.
// @SIDE_EFFECT Updates the row status on the backend.
// @RELATION DEPENDS_ON -> [ApiModule.requestApi]
export async function approveRow<T = unknown>(jobId: string, rowKey: string, languageCode: string | null = null): Promise<T> {
	try {
		const body: Record<string, unknown> = { action: 'approve' };
		if (languageCode) body.language_code = languageCode;
		return await api.requestApi<T>(`/translate/jobs/${jobId}/preview/rows/${rowKey}`, 'PUT', body);
	} catch (error) {
		throw normalizeTranslateError(error, 'Failed to approve row');
	}
}
// #endregion approveRow

// #region editRow [C:2] [TYPE Function] [SEMANTICS translate, preview, edit, row]
// @BRIEF Edit translation for a specific preview row.
// @PRE jobId and rowKey are non-empty strings. translation is a non-empty string.
// @POST Returns updated row data.
// @SIDE_EFFECT Modifies the translation on the backend.
// @RELATION DEPENDS_ON -> [ApiModule.requestApi]
export async function editRow<T = unknown>(jobId: string, rowKey: string, translation: string, languageCode: string | null = null): Promise<T> {
	try {
		const body: Record<string, unknown> = { action: 'edit', translation };
		if (languageCode) body.language_code = languageCode;
		return await api.requestApi<T>(`/translate/jobs/${jobId}/preview/rows/${rowKey}`, 'PUT', body);
	} catch (error) {
		throw normalizeTranslateError(error, 'Failed to edit row');
	}
}
// #endregion editRow

// #region rejectRow [C:2] [TYPE Function] [SEMANTICS translate, preview, reject, row]
// @BRIEF Reject a specific preview row (exclude from translation).
// @PRE jobId and rowKey are non-empty strings.
// @POST Row is marked as rejected and excluded from translation.
// @SIDE_EFFECT Updates the row status on the backend.
// @RELATION DEPENDS_ON -> [ApiModule.requestApi]
export async function rejectRow<T = unknown>(jobId: string, rowKey: string, languageCode: string | null = null): Promise<T> {
	try {
		const body: Record<string, unknown> = { action: 'reject' };
		if (languageCode) body.language_code = languageCode;
		return await api.requestApi<T>(`/translate/jobs/${jobId}/preview/rows/${rowKey}`, 'PUT', body);
	} catch (error) {
		throw normalizeTranslateError(error, 'Failed to reject row');
	}
}
// #endregion rejectRow

// #region acceptPreview [C:2] [TYPE Function] [SEMANTICS translate, preview, accept, finalize]
// @BRIEF Accept all approved rows in a preview session and start translation.
// @PRE jobId is a non-empty string with a finalized preview session.
// @POST Translation run is triggered for the accepted rows.
// @SIDE_EFFECT Creates translation run from accepted preview rows.
// @RELATION DEPENDS_ON -> [ApiModule.postApi]
export async function acceptPreview<T = unknown>(jobId: string): Promise<T> {
	try {
		return await api.postApi<T>(`/translate/jobs/${jobId}/preview/accept`, {});
	} catch (error) {
		throw normalizeTranslateError(error, 'Failed to accept preview');
	}
}
// #endregion acceptPreview

// #region fetchPreviewRecords [C:2] [TYPE Function] [SEMANTICS translate, preview, records]
// @BRIEF Fetch records for a completed preview session.
// @PRE sessionId is a non-empty string.
// @POST Returns preview records with translated content.
// @RELATION DEPENDS_ON -> [ApiModule.fetchApi]
export async function fetchPreviewRecords<T = unknown>(sessionId: string): Promise<T> {
	try {
		return await api.fetchApi<T>(`/translate/preview/${sessionId}/records`);
	} catch (error) {
		throw normalizeTranslateError(error, 'Failed to fetch preview records');
	}
}
// #endregion fetchPreviewRecords
// #endregion TranslateDatasourcesApi
