// #region TranslateSchedulesApi [C:2] [TYPE Module] [SEMANTICS translate, schedules, api, cron]
// @BRIEF API client for translation job scheduling — CRUD, enable/disable, next executions.
// @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 fetchSchedule [C:2] [TYPE Function] [SEMANTICS translate, schedules, fetch]
// @BRIEF Fetch the cron schedule for a translation job.
// @PRE jobId is a non-empty string.
// @POST Returns schedule configuration or null if no schedule exists.
// @RELATION DEPENDS_ON -> [ApiModule.fetchApi]
export async function fetchSchedule<T = unknown>(jobId: string): Promise<T> {
	try {
		return await api.fetchApi<T>(`/translate/jobs/${jobId}/schedule`, { suppressToast: true });
	} catch (error) {
		throw normalizeTranslateError(error, 'Failed to fetch schedule');
	}
}
// #endregion fetchSchedule

// #region setSchedule [C:2] [TYPE Function] [SEMANTICS translate, schedules, set, update]
// @BRIEF Set or update the cron schedule for a translation job.
// @PRE jobId is a non-empty string. payload contains cron expression and enabled flag.
// @POST Returns updated schedule configuration.
// @SIDE_EFFECT Modifies the job's schedule on the backend.
// @RELATION DEPENDS_ON -> [ApiModule.requestApi]
export async function setSchedule<T = unknown>(jobId: string, payload: Record<string, unknown>): Promise<T> {
	try {
		return await api.requestApi<T>(`/translate/jobs/${jobId}/schedule`, 'PUT', payload);
	} catch (error) {
		throw normalizeTranslateError(error, 'Failed to set schedule');
	}
}
// #endregion setSchedule

// #region deleteSchedule [C:2] [TYPE Function] [SEMANTICS translate, schedules, delete]
// @BRIEF Delete the cron schedule for a translation job.
// @PRE jobId is a non-empty string.
// @POST Schedule is removed. No more automated runs will be triggered.
// @SIDE_EFFECT Removes the schedule from the backend.
// @RELATION DEPENDS_ON -> [ApiModule.deleteApi]
export async function deleteSchedule<T = unknown>(jobId: string): Promise<T> {
	try {
		return await api.deleteApi<T>(`/translate/jobs/${jobId}/schedule`);
	} catch (error) {
		throw normalizeTranslateError(error, 'Failed to delete schedule');
	}
}
// #endregion deleteSchedule

// #region enableSchedule [C:2] [TYPE Function] [SEMANTICS translate, schedules, enable]
// @BRIEF Enable an existing schedule for a translation job.
// @PRE jobId is a non-empty string with an existing schedule.
// @POST Schedule is activated and will trigger runs per cron.
// @SIDE_EFFECT Enables the schedule on the backend.
// @RELATION DEPENDS_ON -> [ApiModule.postApi]
export async function enableSchedule<T = unknown>(jobId: string): Promise<T> {
	try {
		return await api.postApi<T>(`/translate/jobs/${jobId}/schedule/enable`, {});
	} catch (error) {
		throw normalizeTranslateError(error, 'Failed to enable schedule');
	}
}
// #endregion enableSchedule

// #region disableSchedule [C:2] [TYPE Function] [SEMANTICS translate, schedules, disable]
// @BRIEF Disable an existing schedule without deleting it.
// @PRE jobId is a non-empty string with an existing schedule.
// @POST Schedule is deactivated. No runs will be triggered until re-enabled.
// @SIDE_EFFECT Disables the schedule on the backend.
// @RELATION DEPENDS_ON -> [ApiModule.postApi]
export async function disableSchedule<T = unknown>(jobId: string): Promise<T> {
	try {
		return await api.postApi<T>(`/translate/jobs/${jobId}/schedule/disable`, {});
	} catch (error) {
		throw normalizeTranslateError(error, 'Failed to disable schedule');
	}
}
// #endregion disableSchedule

// #region fetchNextExecutions [C:2] [TYPE Function] [SEMANTICS translate, schedules, next-executions]
// @BRIEF Fetch upcoming execution times for a job's schedule.
// @PRE jobId is a non-empty string.
// @POST Returns array of upcoming datetime strings.
// @RELATION DEPENDS_ON -> [ApiModule.fetchApi]
export async function fetchNextExecutions<T = unknown>(jobId: string, n: number = 3): Promise<T> {
	try {
		return await api.fetchApi<T>(`/translate/jobs/${jobId}/schedule/next-executions?n=${n}`, { suppressToast: true });
	} catch (error) {
		throw normalizeTranslateError(error, 'Failed to fetch next executions');
	}
}
// #endregion fetchNextExecutions
// #endregion TranslateSchedulesApi
