import { json } from '@sveltejs/kit';
import type { RequestHandler } from './$types';
import { uploadRecipeWithIngredientsDTO, uploadRecipeImage } from '$lib/server/tandoor';

export const POST: RequestHandler = async ({ request }) => {
	const { recipe } = await request.json();

	if (!recipe) {
		return json({ error: 'No recipe provided' }, { status: 400 });
	}

	try {
		const result = await uploadRecipeWithIngredientsDTO(recipe);

		if (!result.success) {
			return json({ error: result.error || 'Failed to upload recipe' }, { status: 500 });
		}

		// Upload image if available
		let imageStatus = null;
		if (result.recipeId && result.imageUrl) {
			imageStatus = await uploadRecipeImage(result.recipeId, result.imageUrl);
			if (!imageStatus.success) {
				console.warn('Image upload failed, but recipe created:', imageStatus.error);
			}
		}

		return json({
			success: true,
			message: 'Recipe successfully imported to Tandoor',
			recipeId: result.recipeId,
			imageUpload: imageStatus?.success ? 'successful' : 'failed'
		});
	} catch (error) {
		console.error('Tandoor upload error:', error);
		return json(
			{
				error: error instanceof Error ? error.message : 'Unknown error occurred'
			},
			{ status: 500 }
		);
	}
};
