<script lang="ts">
	import { deleteCharacters, updateCharacters } from '$gql/Mutations';
	import { omitIdentifiers } from '$gql/Utils';
	import type { Character, UpdateCharacterInput } 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 CharacterForm from '$lib/forms/CharacterForm.svelte';
	import { getContextClient } from '@urql/svelte';
	import type { ModalProps } from 'svelte-modals';

	const client = getContextClient();

	interface Props extends ModalProps {
		character: Character;
	}

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

	function submit(input: UpdateCharacterInput) {
		updateCharacters(client, { ids: character.id, input }).then(modal.close).catch(toastFinally);
	}

	function deleteCharacter() {
		confirmDeletion('Character', character.name, () => {
			deleteCharacters(client, { ids: character.id }).then(modal.close).catch(toastFinally);
		});
	}
</script>

<Dialog title="Edit Character" {...modal}>
	<CharacterForm {initial} {submit}>
		<DeleteButton onclick={deleteCharacter} />
	</CharacterForm>
</Dialog>