import { Static, TSchema } from "@sinclair/typebox";
import { Value } from "@sinclair/typebox/value";
import { HTTPMethods } from "fastify"
import { RouteOptions } from "fastify/types/route.js";

type URLString = string;

export type FirRouteInput<TPayloadSchema extends TSchema> = {
	payload: Static<TPayloadSchema>,
}

export type FirRouteOptions<TIn extends TSchema = TSchema, TOut extends TSchema = TSchema> = {
	method: HTTPMethods,
	url: URLString,
	payloadT: TIn,
	responseT?: TOut,
	handler: (input: FirRouteInput<TIn>) => Static<TOut> | Promise<Static<TOut>>,
}

export const route = <TIn extends TSchema, TOut extends TSchema>(routeOptions: FirRouteOptions<TIn, TOut>): RouteOptions => {
	const {
		method,
		url,
		payloadT,
		handler,
	} = routeOptions;

	const augmentedHandler = (request: Parameters<RouteOptions["handler"]>[0]) => {
		const {
			body,
			query,
		} = request;
		const payload = body ?? query;
		if (Value.Check(payloadT, payload)) {
			return handler({payload});
		} else {
			
			throw new Error("Payload wrong shape.");
		}
	}

	return {
		method,
		url,
		handler: augmentedHandler,
	}
}