<script lang="ts">
import { goto } from '$app/navigation';
import GeschichteEditor from '$lib/geschichte/GeschichteEditor.svelte';
import { getErrorMessage } from '$lib/shared/errors';
import { csrfFetch } from '$lib/shared/cookies';
import type { components } from '$lib/generated/api';

interface Props {
	initialPersons: components['schemas']['Person'][];
}

let { initialPersons }: Props = $props();

let submitting = $state(false);
let errorMessage: string | null = $state(null);

async function handleSubmit(payload: {
	title: string;
	body: string;
	status: 'DRAFT' | 'PUBLISHED';
	personIds: string[];
}) {
	submitting = true;
	errorMessage = null;
	try {
		const res = await csrfFetch('/api/geschichten', {
			method: 'POST',
			headers: { 'Content-Type': 'application/json' },
			body: JSON.stringify({ ...payload, type: 'STORY' })
		});
		if (!res.ok) {
			const code = (await res.json().catch(() => ({})))?.code;
			errorMessage = getErrorMessage(code);
			throw new Error('create failed');
		}
		const created = await res.json();
		goto(`/geschichten/${created.id}`);
	} catch (e) {
		if (!errorMessage) {
			console.error('Story create failed', e);
			errorMessage = getErrorMessage(undefined);
		}
		// Contract: onSubmit rejects on failure — GeschichteEditor catches and
		// keeps its dirty state instead of disarming the unsaved-changes guard.
		throw e;
	} finally {
		submitting = false;
	}
}
</script>

{#if errorMessage}
	<div class="mb-4 rounded border border-danger bg-danger/10 p-3 text-sm text-danger" role="alert">
		{errorMessage}
	</div>
{/if}

<GeschichteEditor initialPersons={initialPersons} onSubmit={handleSubmit} submitting={submitting} />
