import {Request, Response, Router} from "express";
import { promises as fs } from "fs";
import {getConnection} from "typeorm";
import Article from "../entity/Article";
import Note from "../entity/Note";

const domain = process.env.DOMAIN;

export default async function nodeinfo(router: Router) {
	router.get("/.well-known/nodeinfo", (req, res) => {
		res.json({
			links: [
				{
					href: `https://${domain}/nodeinfo/2.0.json`,
					rel: "https://nodeinfo.diaspora.software/ns/schema/2.0"
				},
				{
					href: `https://${domain}/nodeinfo/2.1.json`,
					rel: "https://nodeinfo.diaspora.software/ns/schema/2.1"
				}
			]
		});
		res.end();
	});

	router.get("/nodeinfo/2.0.json", await handleNodeInfo("2.0"));
	router.get("/nodeinfo/2.1.json", await handleNodeInfo("2.1"));
}

async function handleNodeInfo(version: string) {
	const softwareVersion = JSON.parse((await fs.readFile("package.json")).toString()).version;
	const postCount = await getConnection().getRepository(Article).count();
	return async (req: Request, res: Response) => {
		res.json({
			version: version,
			software: {
				name: "shadowfacts_blog",
				version: softwareVersion,
				repository: version === "2.1" ? "https://git.shadowfacts.net/shadowfacts/shadowfacts.net" : undefined
			},
			protocols: ["activitypub"],
			services: {
				inbound: [],
				outbound: ["atom1.0"]
			},
			openRegistrations: false,
			usage: {
				users: {
					total: 1,
					activeHalfyear: 1,
					activeMonth: 1
				},
				localPosts: postCount,
				localComments: await getConnection().getRepository(Note).count()
			}
		});
		res.end();
	};
}
