import express, { Router } from "express";
import fetch from "node-fetch";

const domain = process.env.DOMAIN;

export default function webfinger(router: Router) {
	router.get("/.well-known/webfinger", (req, res) => {
		res.json({
			subject: `acct:blog@${domain}`,
			aliases: [`https://${domain}/ap/actor`],
			links: [
				{
					rel: "self",
					type: "application/activity+json",
					href: `https://${domain}/ap/actor`,
				}
			]
		} as WebfingerResult);
		res.end();
	});
}

export async function queryWebfinger(acct: string): Promise<WebfingerResult> {
	if (acct.startsWith("@")) {
		acct = acct.substring(1);
	}
	const parts = acct.split("@");
	if (parts.length !== 2) {
		throw "Invalid account";
	}
	const response = await fetch(`https://${parts[1]}/.well-known/webfinger?resource=${acct}`);
	const json = await response.json();
	return json as WebfingerResult;
}

export interface WebfingerResult {
	subject: string;
	aliases: string[];
	links: Array<{rel: string, type: string, href: string} | {rel: "https://ostatus.org/schema/1.0/subscribe", template: string}>;
}
