import type { PageServerLoad } from './$types';
import { isS3Enabled } from '$lib/server/storage';
import { getVisibleLevels } from '$lib/server/visibility';

export const load: PageServerLoad = async ({ locals, parent, url }) => {
	const { member } = await parent();
	const searchQuery = url.searchParams.get('q') || '';

	// Get visible visibility levels
	const visibleLevels = getVisibleLevels(member?.role);

	// Build query
	let query = locals.supabase
		.from('documents')
		.select('*')
		.in('visibility', visibleLevels)
		.order('created_at', { ascending: false });

	// Apply server-side search if query provided
	if (searchQuery.trim()) {
		// Use ilike for simple substring search (works without tsvector)
		// Also try full-text search via textSearch if available
		query = query.or(`title.ilike.%${searchQuery}%,description.ilike.%${searchQuery}%,file_name.ilike.%${searchQuery}%`);
	}

	const { data: documents } = await query;

	// Fetch categories
	const { data: categories } = await locals.supabase
		.from('document_categories')
		.select('*')
		.eq('is_active', true)
		.order('sort_order', { ascending: true });

	// Resolve active URL for each document based on current storage settings
	const s3Enabled = await isS3Enabled();
	const documentsWithActiveUrl = (documents || []).map((doc: any) => ({
		...doc,
		// Compute active URL based on storage setting
		active_url: s3Enabled
			? (doc.file_url_s3 || doc.file_path)
			: (doc.file_url_local || doc.file_path)
	}));

	return {
		documents: documentsWithActiveUrl,
		categories: categories || [],
		searchQuery
	};
};

