import { isNonNullish } from "@fern-api/ui-core-utils";
import { BaseOpenApiV3_1ConverterNode, } from "../../../BaseOpenApiV3_1Converter.node";
import { resolveRequestReference } from "../../../utils/3.1/resolveRequestReference";
import { maybeSingleValueToArray } from "../../../utils/maybeSingleValueToArray";
import { RequestMediaTypeObjectConverterNode } from "./RequestMediaTypeObjectConverter.node";
export class RequestBodyObjectConverterNode extends BaseOpenApiV3_1ConverterNode {
    description;
    requestBodiesByContentType;
    constructor(args) {
        super(args);
        this.safeParse();
    }
    parse() {
        const requestBody = resolveRequestReference(this.input, this.context.document);
        if (requestBody == null) {
            this.context.errors.error({
                message: "Expected request body. Received: null",
                path: this.accessPath,
            });
            return undefined;
        }
        Object.entries(requestBody.content).forEach(([contentType, contentTypeObject]) => {
            this.requestBodiesByContentType ??= {};
            this.requestBodiesByContentType[contentType] =
                new RequestMediaTypeObjectConverterNode({
                    input: contentTypeObject,
                    context: this.context,
                    accessPath: this.accessPath,
                    pathId: "content",
                }, contentType);
        });
    }
    convert() {
        return Object.entries(this.requestBodiesByContentType ?? {})
            .flatMap(([contentType, mediaTypeObject]) => {
            const maybeBodies = maybeSingleValueToArray(mediaTypeObject.convert());
            return maybeBodies?.map((body) => ({
                description: this.description,
                contentType,
                body,
            }));
        })
            .filter(isNonNullish);
    }
    convertToWebhookPayload() {
        return Object.values(this.requestBodiesByContentType ?? {})
            .flatMap((mediaTypeObject) => {
            const maybeBodies = maybeSingleValueToArray(mediaTypeObject.convert());
            return maybeBodies?.map((body) => {
                if (body.type !== "alias" && body.type !== "object") {
                    return undefined;
                }
                return {
                    description: this.description,
                    shape: body,
                };
            });
        })
            .filter(isNonNullish);
    }
    webhookExample() {
        return {
            payload: this.requestBodiesByContentType?.["application/json"]?.schema?.example(),
        };
    }
}
