import { ok } from "@atcute/client";
import { mainSchema as putRecordSchema } from "@atcute/atproto/types/repo/putRecord";
import { mainSchema as deleteRecordSchema } from "@atcute/atproto/types/repo/deleteRecord";
import type { Nsid, RecordKey } from "@atcute/lexicons/syntax";
import type { OAuthUserAgent } from "@atcute/oauth-browser-client";
import { createClient } from "$lib/auth/agent";
import type { IssueRecord, RecordView } from "./records";

const ISSUE_COLLECTION = "sh.tangled.repo.issue" as Nsid;

export const putIssue = async (
	agent: OAuthUserAgent,
	rkey: string,
	record: IssueRecord
): Promise<RecordView<IssueRecord>> => {
	const rpc = createClient(agent);
	const { uri, cid } = await ok(
		rpc.call(putRecordSchema, {
			input: {
				repo: agent.sub,
				collection: ISSUE_COLLECTION,
				rkey: rkey as RecordKey,
				record
			}
		})
	);
	return { uri, cid, value: record };
};

export const deleteIssue = async (agent: OAuthUserAgent, rkey: string): Promise<void> => {
	const rpc = createClient(agent);
	await ok(
		rpc.call(deleteRecordSchema, {
			input: { repo: agent.sub, collection: ISSUE_COLLECTION, rkey: rkey as RecordKey }
		})
	);
};
