import { PRECHECKS } from '@andyburke/serverus/handlers/static';
import { get_session, get_user, require_user } from '../utils/prechecks.ts';
import * as CANNED_RESPONSES from '../utils/canned_responses.ts';

export function load() {
	PRECHECKS.PUT = [
		get_session,
		get_user,
		require_user,

		(request: Request, meta: Record<string, any>): Response | undefined => {
			const can_write_own_files = meta.user?.permissions.includes('files.write.own');
			const can_write_all_files = meta.user?.permissions.includes('files.write.all');

			const path = new URL(request.url).pathname;

			const is_to_files = path.toLowerCase().startsWith('/files/');
			const is_to_home_dir = meta.user?.id && path.toLowerCase().startsWith(`/files/users/${meta.user.id}/`);

			const has_permission = is_to_files && (can_write_all_files || (can_write_own_files && is_to_home_dir));

			if (!has_permission) {
				return CANNED_RESPONSES.permission_denied();
			}
		}
	];
}
