import { error } from "@sveltejs/kit";
import { toHttpError } from "$lib/api/load";
import { diffFor } from "$lib/api/diff";
import { renderFormatPatch, renderUnifiedDiff } from "$lib/api/rawdiff";
import { parseRawCommit } from "$lib/api/repo";
import { resolveRepoFromParams } from "$lib/server/repo";
import type { RequestHandler } from "./$types";

export const GET: RequestHandler = async (event) => {
	// the rawCommit matcher already guarantees this shape
	const spec = parseRawCommit(event.params.spec);
	if (!spec) error(404, "Not found");
	// the knot compares hashes case-sensitively, normalize like go-git does
	const ref = spec.ref.toLowerCase();

	const { ctx, view } = await resolveRepoFromParams(event);

	const result = await diffFor(ctx, view.uri, ref, { signal: event.request.signal }).catch(
		(cause) => toHttpError(cause, "Could not load commit")
	);

	// an empty body is a valid empty diff (--allow-empty, some merges), only a
	// missing diff means the commit is absent
	if (result.diff === null || result.diff === undefined) {
		error(404, `${ref} does not exist in this repository`);
	}

	const body =
		spec.format === "patch" ? renderFormatPatch(result.diff) : renderUnifiedDiff(result.diff);

	return new Response(body, {
		headers: {
			"content-type": "text/plain; charset=utf-8",
			"content-disposition": `inline; filename="${ref.slice(0, 7)}.${spec.format}"`
		}
	});
};
