<script lang="ts">
	import { goto } from "$app/navigation";
	import { ok } from "@atcute/client";
	import { mainSchema as createRecordSchema } from "@atcute/atproto/types/repo/createRecord";
	import type { Nsid } from "@atcute/lexicons/syntax";
	import { getAuth } from "$lib/auth.svelte";
	import { createClient } from "$lib/auth/agent";
	import { rkeyFromUri } from "$lib/api/uri";
	import StringForm, { type StringFormData } from "$lib/components/strings/StringForm.svelte";

	const auth = getAuth();
	const user = $derived(auth.currentUser);

	const handleSubmit = async ({ filename, description, content }: StringFormData) => {
		if (!auth.agent) return;
		const rpc = createClient(auth.agent);
		const result = await ok(
			rpc.call(createRecordSchema, {
				input: {
					repo: auth.agent.sub,
					collection: "sh.tangled.string" as Nsid,
					record: {
						$type: "sh.tangled.string",
						filename,
						description,
						contents: content,
						createdAt: new Date().toISOString()
					}
				}
			})
		);
		const rkey = rkeyFromUri(result.uri);
		await goto(`/strings/${user?.handle}/${rkey}`);
	};
</script>

<svelte:head>
	<title>New string &middot; Tangled</title>
</svelte:head>

<div class="mx-auto w-full max-w-screen-lg px-4 py-12">
	<div class="px-2 py-2">
		<h1 class="text-xl font-bold text-foreground-default">Create a new string</h1>
		<p class="text-sm text-foreground-subtle">Store and share code snippets with ease.</p>
	</div>

	<div class="mt-4">
		<StringForm mode="create" onsubmit={handleSubmit} />
	</div>
</div>
