import { Router } from "express";
import { NoteObject, ActorObject } from "./activity";
import { getCachedActor } from "./federate";
import { getConnection } from "typeorm";
import Note from "../entity/Note";
import Article from "../entity/Article";

const domain = process.env.DOMAIN;

interface Comment {
	id: string;
	content: string;
	published: string;
	inReplyTo: string;
	author: ActorObject;
}

async function getConversationComments(conversation: string): Promise<Comment[]> {
	try {
		const notes = await getConnection().getRepository(Note).find({ where: { conversation }, relations: ["actor"] });
		return notes.map(it => {
			return {
				id: it.id,
				content: it.content,
				published: it.published,
				inReplyTo: it.inReplyTo,
				author: {
					id: it.actor.id,
					name: it.actor.displayName,
					icon: it.actor.iconURL
				} as ActorObject
			} as Comment;
		});
	} catch (err) {
		console.log("Couldn't load comments: ", err);
		return [];
	}
}

export default function comments(router: Router) {
	router.get("/ap/conversation/:id", async (req, res) => {
		const comments = await getConversationComments(`https://${domain}/ap/conversation/${req.params.id}`);
		res.json(comments).end();
	});

	router.get("/comments", async (req, res) => {
		const id = req.query.id as string;
		if (!id) {
			res.sendStatus(400).end();
			return;
		}
		try {
			const article = await getConnection().getRepository(Article).findOne(id);
			const comments = await getConversationComments(article.conversation);
			res.json(comments).end();
		} catch (err) {
			console.error("Couldn't retrieve conversation: ", err);
			res.json([]).end();
		}
	});
}
