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

export const GET: RequestHandler = async ({ locals, url }) => {
	const userId = locals.user?.id;
	
	if (!userId) {
		console.log('❌ No userId, returning empty array');
		return json([]);
	}
	
	const cleanUserId = userId.replace('user:', '');
	const db = await getSurrealDB();
	
	// Récupérer les filtres depuis l'URL
	const screenTypeFilter = url.searchParams.get('screen_type');
	
	try {
		// Récupérer les prestataires liés à l'utilisateur
		const userProvidersResult = await db.query<[any[]]>(
			'SELECT out.* as provider FROM works_for WHERE in = type::thing("user", $userId) AND ended_at = NONE',
			{ userId: cleanUserId }
		);
		const userProviderIds = (userProvidersResult[0] || []).map((r: any) => r.provider?.id);
		
		// Charger toutes les locations actives (publiques ou du provider de l'utilisateur)
		let whereConditions = ['is_active = true'];
		const queryParams: Record<string, any> = { providerIds: userProviderIds };
		
		if (userProviderIds.length > 0) {
			whereConditions.push('(is_public = true OR provider IN $providerIds)');
		} else {
			whereConditions.push('is_public = true');
		}
		
		const whereClause = whereConditions.join(' AND ');
		
		// Récupérer les locations
		const locationsResult = await db.query<[any[]]>(
			`SELECT 
				*,
				provider.name as provider_name,
				provider.id as provider_id,
				country.name_fr as country_name_fr,
				country.name_en as country_name_en,
				country.code as country_code,
				location_type.name as location_type_name,
				location_type.icon as location_type_icon
			FROM location 
			WHERE ${whereClause}
			FETCH provider, country, location_type`,
			queryParams
		);
		
		// Récupérer tous les screens actifs avec filtre optionnel sur le type
		let screenQuery = 'SELECT * FROM screen WHERE is_active = true';
		const screenParams: Record<string, any> = {};
		
		if (screenTypeFilter) {
			screenQuery += ' AND type = $screenType';
			screenParams.screenType = screenTypeFilter;
		}
		
		const screensResult = await db.query<[any[]]>(screenQuery, screenParams);
		const allScreens = screensResult[0] || [];
		
		const normalizeRecordId = (value: any): string | null => {
			if (!value) return null;
			if (typeof value === 'string') return value;
			if (typeof value?.toString === 'function') return value.toString();
			if (typeof value?.id === 'string') return value.id;
			if (typeof value?.id?.toString === 'function') return value.id.toString();
			return null;
		};

		const normalizeRecordKey = (value: any): string | null => {
			const raw = normalizeRecordId(value);
			if (!raw) return null;
			return raw.includes(':') ? raw.split(':').pop() || raw : raw;
		};

		// Associer les screens aux locations
		const locations = (locationsResult[0] || []).map((location: any) => {
			const locationId = normalizeRecordId(location.id);
			const locationKey = normalizeRecordKey(location.id);
			const screens = allScreens.filter((screen: any) => {
				const screenLocationId = normalizeRecordId(screen.location);
				const screenLocationKey = normalizeRecordKey(screen.location);
				if (!locationId || !screenLocationId) return false;
				return (
					screenLocationId === locationId ||
					(locationKey !== null && screenLocationKey !== null && locationKey === screenLocationKey)
				);
			});
			return {
				...location,
				screens
			};
		});
		
		const serializedLocations = serializeRecords(locations);
		
		// Count screens
		const totalScreens = serializedLocations.reduce((sum: number, loc: any) => sum + (loc.screens?.length || 0), 0);
		
		// Locations loaded successfully
		
		return json(serializedLocations);
	} catch (error) {
		console.error('❌ Error loading locations:', error);
		return json([]);
	}
};
