import { client } from '$lib/minio';

/** @type {import('./$types').RequestHandler} */
export async function GET({ params }) {
	const prefix = params.vorgang ? `${params.vorgang}/` : '';
	let stream = client.listObjectsV2('tatort', prefix, false, '');
	const result = new ReadableStream({
		start(controller) {
			stream.on('data', (data) => {
				if (prefix === '') {
					if (data.prefix)
						controller.enqueue(`${JSON.stringify({ ...data, name: data.prefix.slice(0, -1) })}\n`);
					return;
				}

				const name = data.name.slice(prefix.length);
				if (name === 'config.json') return;

				controller.enqueue(`${JSON.stringify({ ...data, name, prefix })}\n`);
			});
			stream.on('end', () => {
				controller.close();
			});
		},
		cancel() {
			stream.destroy();
		}
	});

	return new Response(result, {
		headers: {
			'content-type': 'text/event-stream'
		}
	});
}
