import {Router} from "express";
import {queryWebfinger} from "./webfinger";

const domain = process.env.DOMAIN;

export default async function interact(router: Router) {
	router.post("/interact", async (req, res) => {
		const permalink = req.body.permalink;
		const acct = req.body.remote_follow.acct;
		const webfingerResult = await queryWebfinger(acct);
		const link = webfingerResult.links.find((l) => l.rel === "http://ostatus.org/schema/1.0/subscribe");
		if (link && 'template' in link) {
			res.redirect(link.template.replace("{uri}", `https://${domain}${permalink}`));
		} else {
			res.status(400).send("Unable to find remote subscribe URL");
		}
	});
}
