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

export const load: PageServerLoad = async ({ locals, parent }) => {
	const { member } = await parent();

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

	// Fetch documents with all URL columns
	const { data: documents } = await locals.supabase
		.from('documents')
		.select('*')
		.in('visibility', visibleLevels)
		.order('created_at', { ascending: false });

	// 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 || []
	};
};

function getVisibleLevels(role: string | undefined): string[] {
	switch (role) {
		case 'admin':
			return ['public', 'members', 'board', 'admin'];
		case 'board':
			return ['public', 'members', 'board'];
		default:
			return ['public', 'members'];
	}
}
