import { Request } from "./Request";
import { MiddlewareRequest } from "../middleware";
import { FastifyReply } from "fastify";

type RequestConstructor<T> = new () => Request<T>;
export type RouteMiddlewareHandler<T> = (request: MiddlewareRequest<T>, reply: FastifyReply) => Promise<void> | void;

export function handleRequest<T>(requests: RequestConstructor<T>[], handle: RouteMiddlewareHandler<T>): RouteMiddlewareHandler<T>
{
	return async (fastifyRequest, fastifyReply) => {
		// Request parsing
		for (let requestClass of requests) {
			let request = new requestClass();
			let response = await request.handle(fastifyRequest, fastifyReply);
			if (response) {
				fastifyReply.send(response);
				return;
			}
		}
		// Requests have been parsed/handled successfully, proceed to process the request
		await (<any>handle)(fastifyRequest, fastifyReply);
	}
}
