import { client } from '$lib/minio';
import { fail } from '@sveltejs/kit';

import caseNumberOccupied from '$lib/helper/caseNumberOccupied';

/** @type {import('./$types').Actions} */
export const actions = {
	default: async ({ request }) => {
		const data = await request.formData();
		const caseNumber = data.get('caseNumber');
		const description = data.get('description');

		if (!caseNumber) {
			return fail(400, {
				caseNumber,
				description,
				error: { caseNumber: 'Es muss eine Vorgangsnummer vorhanden sein.' }
			});
		}

		if (await caseNumberOccupied(`${caseNumber}`)) {
			return fail(400, {
				caseNumber,
				description,
				error: { caseNumber: 'Die Vorgangsnummer wurde im System bereits angelegt.' }
			});
		}

		const config = `${JSON.stringify({ caseNumber, description, version: 1 })}\n`;

		await client.putObject('tatort', `${caseNumber}/config.json`, config, {
			'Content-Type': 'application/json'
		});

		return { success: true };
	}
};
