import caseNumberOccupied from '$lib/helper/caseNumberOccupied';
import { fail, redirect } from '@sveltejs/kit';

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

		if (!caseNumber) {
			return fail(400, {
				success: false,
				caseNumber,
				error: { caseNumber: 'Die Vorgangsnummer darf nicht leer sein.' }
			});
		}

		if (!(await caseNumberOccupied(caseNumber))) {
			return fail(400, {
				success: false,
				caseNumber,
				error: { caseNumber: 'Die Vorgangsnummer existiert in dieser Anwendung nicht.' }
			});
		}
		throw redirect(303, `/list/${caseNumber}`);
	}
};
