import { commonRequest } from "./commonRequest.js";
import { commonUrlBuilder } from "./commonUrlBuilder.js";

import type { RouteParamsInterface, RouteRequestInterface, RouteResponseInterface } from "./commonUrlBuilder.js";
import type { WithOptional } from "../../helpers.js";
import type { BaseOptions } from "../../options.js";

/**
 * Create a uri builder and request function for your specific plugin depending
 * on the rest root and additional parameters.
 *
 * @param options
 * @see urlBuilder
 * @see request
 */
function createRequestFactory(options: BaseOptions) {
    const urlBuilder = (passOptions: WithOptional<Parameters<typeof commonUrlBuilder>[0], "options">) =>
        commonUrlBuilder({
            ...passOptions,
            options: {
                restNamespace: options.restNamespace,
                restNonce: options.restNonce,
                restQuery: options.restQuery,
                restRoot: options.restRoot,
                restPathObfuscateOffset: options.restPathObfuscateOffset,
            },
        });

    const request = <
        Request extends RouteRequestInterface,
        Params extends RouteParamsInterface,
        Response extends RouteResponseInterface,
    >(
        passOptions: WithOptional<Parameters<typeof commonRequest>[0], "options"> & {
            params?: Params;
            request?: Request;
        },
    ): Promise<Response> =>
        commonRequest({
            ...passOptions,
            options: {
                restNamespace: options.restNamespace,
                restNonce: options.restNonce,
                restQuery: options.restQuery,
                restRoot: options.restRoot,
                restRecreateNonceEndpoint: options.restRecreateNonceEndpoint,
                restPathObfuscateOffset: options.restPathObfuscateOffset,
            },
        });

    return {
        urlBuilder,
        request,
    };
}

export { createRequestFactory };
