<script lang="ts">
	import { deleteNamespaces, updateNamespaces } from '$gql/Mutations';
	import { omitIdentifiers } from '$gql/Utils';
	import type { Namespace, UpdateNamespaceInput } 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 NamespaceForm from '$lib/forms/NamespaceForm.svelte';
	import { getContextClient } from '@urql/svelte';
	import type { ModalProps } from 'svelte-modals';

	const client = getContextClient();

	interface Props extends ModalProps {
		namespace: Namespace;
	}

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

	function submit(input: UpdateNamespaceInput) {
		updateNamespaces(client, { ids: namespace.id, input }).then(modal.close).catch(toastFinally);
	}

	function deleteNamespace() {
		confirmDeletion('Namespace', namespace.name, () => {
			deleteNamespaces(client, { ids: namespace.id }).then(modal.close).catch(toastFinally);
		});
	}
</script>

<Dialog title="Edit Namespace" {...modal}>
	<NamespaceForm {initial} {submit}>
		<DeleteButton onclick={deleteNamespace} />
	</NamespaceForm>
</Dialog>
