<script lang="ts">
	import { deleteWorlds, updateWorlds } from '$gql/Mutations';
	import { omitIdentifiers } from '$gql/Utils';
	import type { UpdateWorldInput, World } from '$gql/graphql';
	import { toastFinally } from '$lib/Toasts';
	import { confirmDeletion } from '$lib/Utils';
	import DeleteButton from '$lib/components/DeleteButton.svelte';
	import Dialog from '$lib/components/Dialog.svelte';
	import WorldForm from '$lib/forms/WorldForm.svelte';
	import { getContextClient } from '@urql/svelte';
	import type { ModalProps } from 'svelte-modals';

	const client = getContextClient();

	interface Props extends ModalProps {
		world: World;
	}

	let { world, ...modal }: Props = $props();
	const initial = omitIdentifiers(world);

	function submit(input: UpdateWorldInput) {
		updateWorlds(client, { ids: world.id, input }).then(modal.close).catch(toastFinally);
	}

	function deleteWorld() {
		confirmDeletion('World', world.name, () => {
			deleteWorlds(client, { ids: world.id }).then(modal.close).catch(toastFinally);
		});
	}
</script>

<Dialog title="Edit World" {...modal}>
	<WorldForm {initial} {submit}>
		<DeleteButton onclick={deleteWorld} />
	</WorldForm>
</Dialog>
