import { createHmac } from "node:crypto";
import { error } from "@sveltejs/kit";
import { getConfig } from "$lib/server/config";
import type { RequestHandler } from "./$types";

// half a day, the same as what the service puts on the image
const MAX_AGE = 43200;

const DID = /^did:[a-z]+:[a-zA-Z0-9._:%-]{1,256}$/;

// the service ignores anything else, so there is no point passing it on
const PASSED_THROUGH = ["size", "format"];

export const GET: RequestHandler = ({ params, url }) => {
	const did = params.did;
	if (!DID.test(did)) error(400, "Not a did");

	const { avatarUrl, avatarSecret } = getConfig();
	if (!avatarSecret) error(404, "Avatars are not configured");

	const query = new URLSearchParams();
	for (const key of PASSED_THROUGH) {
		const value = url.searchParams.get(key);
		if (value) query.set(key, value);
	}

	const signature = createHmac("sha256", avatarSecret).update(did).digest("hex");
	const target = `${avatarUrl}/${signature}/${did}${query.size ? `?${query}` : ""}`;
	return new Response(null, {
		status: 302,
		headers: { location: target, "cache-control": `public, max-age=${MAX_AGE}` }
	});
};
