<script lang="ts">
	import { deleteArtists, updateArtists } from '$gql/Mutations';
	import { omitIdentifiers } from '$gql/Utils';
	import type { Artist, UpdateArtistInput } 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 ArtistForm from '$lib/forms/ArtistForm.svelte';
	import { getContextClient } from '@urql/svelte';
	import type { ModalProps } from 'svelte-modals';

	const client = getContextClient();

	interface Props extends ModalProps {
		artist: Artist;
	}

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

	function submit(input: UpdateArtistInput) {
		updateArtists(client, { ids: artist.id, input }).then(modal.close).catch(toastFinally);
	}

	function deleteArtist() {
		confirmDeletion('Artist', artist.name, () => {
			deleteArtists(client, { ids: artist.id }).then(modal.close).catch(toastFinally);
		});
	}
</script>

<Dialog title="Edit Artist" {...modal}>
	<ArtistForm {initial} {submit}>
		<DeleteButton onclick={deleteArtist} />
	</ArtistForm>
</Dialog>
