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

export class Request<T = unknown>
{
	/**
	 * Handle the incoming request
	 */
	public async handle(request: MiddlewareRequest<T>, reply: FastifyReply) {
		if (!this.checkFormat(request)) {
			reply.status(400);
			return {
				status: "Bad request"
			};
		}
		if (!await this.isAuthorized(request)) {
			reply.status(403);
			return {
				status: "Forbidden"
			};
		}
		try {
			await this.validate(request);
		} catch(errors) {
			reply.status(422);
			return {
				status: "Unprocessable entities",
				errors
			};
		}
	}

	// Overridable ---------------------------------------------------------------------------------

	/**
	 * Check the format of the given request
	 */
	public checkFormat(request: MiddlewareRequest<T>) {
		return true;
	}

	/**
	 * Check if the user is authorized to make this request
	 */
	public async isAuthorized(request: MiddlewareRequest<T>) {
		return true;
	}

	/**
	 * Validate the request and return any errors
	 */
	public async validate(request: MiddlewareRequest<T>): Promise<any|undefined> {
		return undefined;
	}
}

Request.apply(undefined);
