import type { RequestHandler } from './$types';
import { json } from '@sveltejs/kit';
import { getSurrealDB } from '$lib/server/db';

export const POST: RequestHandler = async ({ request, locals }) => {
	// Vérifier que l'utilisateur est admin
	if (locals.user?.role !== 'admin') {
		return json({ error: 'Unauthorized' }, { status: 403 });
	}

	const { translations } = await request.json();
	const db = await getSurrealDB();

	try {
		// Pour chaque traduction
		for (const trans of translations) {
			const { id, slug, zone, description, fr, en, es, de } = trans;

			// Créer l'objet translations
			const translationsObj: Record<string, string> = {};
			if (fr) translationsObj['fr'] = fr;
			if (en) translationsObj['en'] = en;
			if (es) translationsObj['es'] = es;
			if (de) translationsObj['de'] = de;

			if (id) {
				// Mise à jour
				await db.query(
					`UPDATE ${id} SET 
						slug = $slug,
						zone = $zone,
						description = $description,
						translations = $translations,
						updated_at = time::now()`,
					{
						slug,
						zone,
						description: description || null,
						translations: translationsObj
					}
				);
			} else {
				// Création
				await db.query(
					'CREATE glossary CONTENT { slug: $slug, zone: $zone, description: $description, translations: $translations }',
					{
						slug,
						zone,
						description: description || null,
						translations: translationsObj
					}
				);
			}
		}

		return json({ success: true });
	} catch (error) {
		console.error('Error saving translations:', error);
		return json({ error: 'Failed to save translations' }, { status: 500 });
	}
};
