import { json, error } from '@sveltejs/kit';
import type { RequestHandler } from './$types';
import { getSurrealDB } from '$lib/server/db';
import { uploadToR2, generateMediaKey, getMediaType, isAllowedFile } from '$lib/server/cloudflare';
import { generateThumbnail, getVideoMetadata } from '$lib/server/ffmpeg';

export const POST: RequestHandler = async ({ request, locals }) => {
	const userId = locals.user?.id;
	
	if (!userId) {
		throw error(401, 'Non authentifié');
	}
	
	const cleanUserId = userId.replace('user:', '');
	console.log('Media upload endpoint - userId:', userId, 'cleanUserId:', cleanUserId);
	
	// Get user's company
	const db = await getSurrealDB();
	const userResult = await db.query<[any[]]>(
		'SELECT company FROM user WHERE id = type::thing("user", $userId)',
		{ userId: cleanUserId }
	);
	const userCompany = userResult[0]?.[0]?.company;
	
	try {
		const formData = await request.formData();
		const file = formData.get('file') as File;
		const folderId = formData.get('folder') as string | null;
		const customThumbnail = formData.get('thumbnail') as File | null;
		const existingThumbnailUrl = formData.get('thumbnail_url') as string | null;
		
		if (!file) {
			throw error(400, 'Aucun fichier fourni');
		}
		
		// Vérifier le fichier
		const { allowed, reason } = isAllowedFile(file.type);
		if (!allowed) {
			throw error(400, reason || 'Fichier non autorisé');
		}
		
		// Générer la clé R2
		const key = generateMediaKey(cleanUserId, file.name);
		
		// Upload sur R2
		const { url } = await uploadToR2(file, key, file.type, {
			originalName: file.name,
			userId: cleanUserId
		});
		
		// Déterminer le type de média
		const mediaType = getMediaType(file.type);
		
		// Générer un thumbnail pour les vidéos
		let thumbnailUrl = null;
		let videoMetadata = null;
		
		// Priorité: 1. Thumbnail personnalisée uploadée, 2. URL existante, 3. Auto-génération
		if (customThumbnail && customThumbnail.size > 0) {
			// Upload de la thumbnail personnalisée
			try {
				const thumbnailKey = `thumbnails/${cleanUserId}/${Date.now()}_custom_thumb.${customThumbnail.name.split('.').pop()}`;
				const thumbnailResult = await uploadToR2(customThumbnail, thumbnailKey, customThumbnail.type);
				thumbnailUrl = thumbnailResult.url;
				console.log('Custom thumbnail uploaded:', thumbnailUrl);
			} catch (thumbErr) {
				console.warn('Warning: Could not upload custom thumbnail:', thumbErr);
			}
		} else if (existingThumbnailUrl) {
			// Utiliser l'URL existante (depuis la médiathèque)
			thumbnailUrl = existingThumbnailUrl;
			console.log('Using existing thumbnail URL:', thumbnailUrl);
		}
		
		// Si pas de thumbnail custom et c'est une vidéo, générer automatiquement
		if (!thumbnailUrl && mediaType === 'video') {
			try {
				// Convertir File en Buffer
				const arrayBuffer = await file.arrayBuffer();
				const buffer = Buffer.from(arrayBuffer);
				
				// Générer le thumbnail
				const thumbnailBuffer = await generateThumbnail(buffer, 1);
				
				// Extraire les métadonnées
				videoMetadata = await getVideoMetadata(buffer);
				
				// Upload du thumbnail vers R2
				const thumbnailKey = `thumbnails/${cleanUserId}/${Date.now()}_${file.name.replace(/\.[^/.]+$/, '')}_thumb.jpg`;
				const thumbnailResult = await uploadToR2(
						new File([new Uint8Array(thumbnailBuffer)], 'thumbnail.jpg', { type: 'image/jpeg' }),
					thumbnailKey,
					'image/jpeg'
				);
				thumbnailUrl = thumbnailResult.url;
				
				console.log('Thumbnail généré:', thumbnailUrl);
			} catch (thumbErr) {
				console.warn('Warning: Could not generate thumbnail for video:', thumbErr);
				// Ne pas bloquer si le thumbnail échoue
			}
		}
		
		// Extraire le company ID si présent
		let companyId = null;
		if (userCompany) {
			companyId = typeof userCompany === 'string' 
				? userCompany.replace('company:', '') 
				: userCompany.id?.replace?.('company:', '') || userCompany.id;
		}
		
		const result = await db.query(`
			CREATE media SET
				user = type::thing("user", $userId),
				uploaded_by = type::thing("user", $userId),
				${companyId ? 'company = type::thing("company", $companyId),' : ''}
				name = $name,
				original_name = $originalName,
				type = $mediaType,
				media_type = $mediaType,
				mime_type = $mimeType,
				cloudflare_key = $cloudflareKey,
				url = $url,
				${thumbnailUrl ? 'thumbnail_url = $thumbnailUrl,' : ''}
				${videoMetadata ? 'metadata = $metadata,' : ''}
				size_bytes = $sizeBytes,
				tags = [],
				is_favorite = false,
				created_at = time::now(),
				updated_at = time::now()
		`, {
			userId: cleanUserId,
			...(companyId && { companyId }),
			name: file.name.replace(/\.[^/.]+$/, ''),
			originalName: file.name,
			mediaType,
			mimeType: file.type,
			cloudflareKey: key,
			url,
			...(thumbnailUrl && { thumbnailUrl }),
			...(videoMetadata && { metadata: videoMetadata }),
			sizeBytes: file.size
		});
		
		console.log('Media upload endpoint - Media created:', result[0]);
		
		return json({
			success: true,
			media: result[0][0] || result[0] // Handle both array and single record
		});
	} catch (err: any) {
		console.error('Upload error:', err);
		if (err.status) throw err;
		throw error(500, err.message || 'Erreur lors de l\'upload');
	}
};
