import express, { Router } from "express";
import { promises as fs } from "fs";

const domain = process.env.DOMAIN;
const pubKeyPemPath = process.env.PUB_KEY_PEM;

export default async function actor(router: Router) {
	if (!pubKeyPemPath) {
		return;
	}
	const pubKeyPem = (await fs.readFile(pubKeyPemPath)).toString();
	const actorObj = {
		"@context": [
			"https://www.w3.org/ns/activitystreams",
			"https://w3id.org/security/v1"
		],
		"type": "Person",
		"id": `https://${domain}/ap/actor`,
		"preferredUsername": "blog",
		"name": "shadowfacts' blog",
		"icon": {
			"type": "Image",
			"mediaType": "image/png",
			"url": `https://${domain}/shadowfacts.png`
		},
		"inbox": `https://${domain}/ap/inbox`,
		"followers": `https://${domain}/ap/actor/followers`,
		"publicKey": {
			"id": `https://${domain}/ap/actor#main-key`,
			"owner": `https://${domain}/ap/actor`,
			"publicKeyPem": pubKeyPem
		}
	};

	router.get("/ap/actor", (req, res) => {
		if (req.accepts("text/html")) {
			res.redirect("/");
		} else {
			res.type("application/activity+json");
			res.json(actorObj);
			res.end();
		}
	});
}
