import { IpcClient as TorrentIpc } from "@autoplex-api/torrent";
import { IteratorNext, MiddlewareRequest, FastifyReply, Status, respond } from "@autoplex/webserver";
import { ISerializedTorrent } from "@autoplex-api/torrent";
import Application from "../../../Application";

/**
 * The parameter types for the auth middleware
 */
export interface ITorrentMiddleware {
	torrent: ISerializedTorrent
}

/**
 * Ensure that a valid authentication token is provided
 */
export async function torrent<T extends ITorrentMiddleware>(request: MiddlewareRequest<T>, reply: FastifyReply, next: IteratorNext) {
	let ipc = Application.instance().service<TorrentIpc>("Torrent");
	let torrentId: string|undefined = (<any>request.params)["torrentId"];
	if (torrentId === undefined) {
		return respond(reply, Status.BadRequest);
	}
	if (!(await ipc.has(torrentId))) {
		return respond(reply, Status.NotFound);
	}
	request.middlewareParams = Object.assign(request.middlewareParams ?? {}, {
		torrent: (await ipc.details([torrentId]))[0]
	});
	next();
}
