"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
/* eslint-disable @typescript-eslint/no-use-before-define */
/* eslint-disable no-await-in-loop */
/* eslint-disable no-restricted-syntax */
/* eslint-disable no-use-before-define */
const graphql_type_json_1 = require("graphql-type-json");
const graphql_1 = require("graphql");
const graphql_scalars_1 = require("graphql-scalars");
const formatName_1 = __importDefault(require("../utilities/formatName"));
const combineParentName_1 = __importDefault(require("../utilities/combineParentName"));
const withNullableType_1 = __importDefault(require("./withNullableType"));
const formatLabels_1 = require("../../utilities/formatLabels");
const relationshipPromise_1 = __importDefault(require("../../fields/richText/relationshipPromise"));
const formatOptions_1 = __importDefault(require("../utilities/formatOptions"));
const buildWhereInputType_1 = __importDefault(require("./buildWhereInputType"));
const buildBlockType_1 = __importDefault(require("./buildBlockType"));
function buildObjectType({ payload, name, fields, parentName, baseFields = {}, forceNullable, }) {
    const fieldToSchemaMap = {
        number: (objectTypeConfig, field) => ({
            ...objectTypeConfig,
            [field.name]: { type: (0, withNullableType_1.default)(field, graphql_1.GraphQLFloat) },
        }),
        text: (objectTypeConfig, field) => ({
            ...objectTypeConfig,
            [field.name]: { type: (0, withNullableType_1.default)(field, graphql_1.GraphQLString) },
        }),
        email: (objectTypeConfig, field) => ({
            ...objectTypeConfig,
            [field.name]: { type: (0, withNullableType_1.default)(field, graphql_scalars_1.EmailAddressResolver) },
        }),
        textarea: (objectTypeConfig, field) => ({
            ...objectTypeConfig,
            [field.name]: { type: (0, withNullableType_1.default)(field, graphql_1.GraphQLString) },
        }),
        code: (objectTypeConfig, field) => ({
            ...objectTypeConfig,
            [field.name]: { type: (0, withNullableType_1.default)(field, graphql_1.GraphQLString) },
        }),
        date: (objectTypeConfig, field) => ({
            ...objectTypeConfig,
            [field.name]: { type: (0, withNullableType_1.default)(field, graphql_scalars_1.DateTimeResolver) },
        }),
        point: (objectTypeConfig, field) => ({
            ...objectTypeConfig,
            [field.name]: { type: (0, withNullableType_1.default)(field, new graphql_1.GraphQLList(graphql_1.GraphQLFloat)) },
        }),
        richText: (objectTypeConfig, field) => ({
            ...objectTypeConfig,
            [field.name]: {
                type: (0, withNullableType_1.default)(field, graphql_type_json_1.GraphQLJSON),
                async resolve(parent, args, context) {
                    if (args.depth > 0) {
                        await (0, relationshipPromise_1.default)({
                            req: context.req,
                            siblingDoc: parent,
                            depth: args.depth,
                            field,
                            showHiddenFields: false,
                        });
                    }
                    return parent[field.name];
                },
                args: {
                    depth: {
                        type: graphql_1.GraphQLInt,
                    },
                },
            },
        }),
        upload: (objectTypeConfig, field) => {
            const { relationTo, label } = field;
            const uploadName = (0, combineParentName_1.default)(parentName, label === false ? (0, formatLabels_1.toWords)(field.name, true) : label);
            // If the relationshipType is undefined at this point,
            // it can be assumed that this blockType can have a relationship
            // to itself. Therefore, we set the relationshipType equal to the blockType
            // that is currently being created.
            const type = payload.collections[relationTo].graphQL.type || newlyCreatedBlockType;
            const uploadArgs = {};
            if (payload.config.localization) {
                uploadArgs.locale = {
                    type: payload.types.localeInputType,
                };
                uploadArgs.fallbackLocale = {
                    type: payload.types.fallbackLocaleInputType,
                };
            }
            const relatedCollectionSlug = field.relationTo;
            const upload = {
                args: uploadArgs,
                type,
                extensions: { complexity: 20 },
                async resolve(parent, args, context) {
                    const value = parent[field.name];
                    const locale = args.locale || context.req.locale;
                    const fallbackLocale = args.fallbackLocale || context.req.fallbackLocale;
                    const id = value;
                    if (id) {
                        const relatedDocument = await context.req.payloadDataLoader.load(JSON.stringify([
                            relatedCollectionSlug,
                            id,
                            0,
                            0,
                            locale,
                            fallbackLocale,
                            false,
                            false,
                        ]));
                        return relatedDocument || null;
                    }
                    return null;
                },
            };
            const whereFields = payload.collections[relationTo].config.fields;
            upload.args.where = {
                type: (0, buildWhereInputType_1.default)(uploadName, whereFields, uploadName),
            };
            return {
                ...objectTypeConfig,
                [field.name]: upload,
            };
        },
        radio: (objectTypeConfig, field) => ({
            ...objectTypeConfig,
            [field.name]: {
                type: (0, withNullableType_1.default)(field, new graphql_1.GraphQLEnumType({
                    name: (0, combineParentName_1.default)(parentName, field.name),
                    values: (0, formatOptions_1.default)(field),
                })),
            },
        }),
        checkbox: (objectTypeConfig, field) => ({
            ...objectTypeConfig,
            [field.name]: { type: (0, withNullableType_1.default)(field, graphql_1.GraphQLBoolean) },
        }),
        select: (objectTypeConfig, field) => {
            const fullName = (0, combineParentName_1.default)(parentName, field.name);
            let type = new graphql_1.GraphQLEnumType({
                name: fullName,
                values: (0, formatOptions_1.default)(field),
            });
            type = field.hasMany ? new graphql_1.GraphQLList(type) : type;
            type = (0, withNullableType_1.default)(field, type);
            return {
                ...objectTypeConfig,
                [field.name]: { type },
            };
        },
        relationship: (objectTypeConfig, field) => {
            const { relationTo, label } = field;
            const isRelatedToManyCollections = Array.isArray(relationTo);
            const hasManyValues = field.hasMany;
            const relationshipName = (0, combineParentName_1.default)(parentName, label === false ? (0, formatLabels_1.toWords)(field.name, true) : label);
            let type;
            let relationToType = null;
            if (Array.isArray(relationTo)) {
                relationToType = new graphql_1.GraphQLEnumType({
                    name: `${relationshipName}_RelationTo`,
                    values: relationTo.reduce((relations, relation) => ({
                        ...relations,
                        [(0, formatName_1.default)(relation)]: {
                            value: relation,
                        },
                    }), {}),
                });
                const types = relationTo.map((relation) => payload.collections[relation].graphQL.type);
                type = new graphql_1.GraphQLObjectType({
                    name: `${relationshipName}_Relationship`,
                    fields: {
                        relationTo: {
                            type: relationToType,
                        },
                        value: {
                            type: new graphql_1.GraphQLUnionType({
                                name: relationshipName,
                                types,
                                async resolveType(data, { req }) {
                                    return payload.collections[data.collection].graphQL.type.name;
                                },
                            }),
                        },
                    },
                });
            }
            else {
                ({ type } = payload.collections[relationTo].graphQL);
            }
            // If the relationshipType is undefined at this point,
            // it can be assumed that this blockType can have a relationship
            // to itself. Therefore, we set the relationshipType equal to the blockType
            // that is currently being created.
            type = type || newlyCreatedBlockType;
            const relationshipArgs = {};
            if (payload.config.localization) {
                relationshipArgs.locale = {
                    type: payload.types.localeInputType,
                };
                relationshipArgs.fallbackLocale = {
                    type: payload.types.fallbackLocaleInputType,
                };
            }
            const relationship = {
                args: relationshipArgs,
                type: hasManyValues ? new graphql_1.GraphQLList(type) : type,
                extensions: { complexity: 10 },
                async resolve(parent, args, context) {
                    const value = parent[field.name];
                    const locale = args.locale || context.req.locale;
                    const fallbackLocale = args.fallbackLocale || context.req.fallbackLocale;
                    let relatedCollectionSlug = field.relationTo;
                    if (hasManyValues) {
                        const results = [];
                        const resultPromises = [];
                        const createPopulationPromise = async (relatedDoc, i) => {
                            let id = relatedDoc;
                            let collectionSlug = field.relationTo;
                            if (isRelatedToManyCollections) {
                                collectionSlug = relatedDoc.relationTo;
                                id = relatedDoc.value;
                            }
                            const result = await context.req.payloadDataLoader.load(JSON.stringify([
                                collectionSlug,
                                id,
                                0,
                                0,
                                locale,
                                fallbackLocale,
                                false,
                                false,
                            ]));
                            if (result) {
                                if (isRelatedToManyCollections) {
                                    results[i] = {
                                        relationTo: collectionSlug,
                                        value: {
                                            ...result,
                                            collection: collectionSlug,
                                        },
                                    };
                                }
                                else {
                                    results[i] = result;
                                }
                            }
                        };
                        if (value) {
                            value.forEach((relatedDoc, i) => {
                                resultPromises.push(createPopulationPromise(relatedDoc, i));
                            });
                        }
                        await Promise.all(resultPromises);
                        return results;
                    }
                    let id = value;
                    if (isRelatedToManyCollections && value) {
                        id = value.value;
                        relatedCollectionSlug = value.relationTo;
                    }
                    if (id) {
                        id = id.toString();
                        const relatedDocument = await context.req.payloadDataLoader.load(JSON.stringify([
                            relatedCollectionSlug,
                            id,
                            0,
                            0,
                            locale,
                            fallbackLocale,
                            false,
                            false,
                        ]));
                        if (relatedDocument) {
                            if (isRelatedToManyCollections) {
                                return {
                                    relationTo: relatedCollectionSlug,
                                    value: {
                                        ...relatedDocument,
                                        collection: relatedCollectionSlug,
                                    },
                                };
                            }
                            return relatedDocument;
                        }
                        return null;
                    }
                    return null;
                },
            };
            return {
                ...objectTypeConfig,
                [field.name]: relationship,
            };
        },
        array: (objectTypeConfig, field) => {
            const fullName = (0, combineParentName_1.default)(parentName, field.label === false ? (0, formatLabels_1.toWords)(field.name, true) : field.label);
            const type = buildObjectType({
                payload,
                name: fullName,
                fields: field.fields,
                parentName: fullName,
                forceNullable,
            });
            const arrayType = new graphql_1.GraphQLList((0, withNullableType_1.default)(field, type));
            return {
                ...objectTypeConfig,
                [field.name]: { type: arrayType },
            };
        },
        group: (objectTypeConfig, field) => {
            const fullName = (0, combineParentName_1.default)(parentName, field.label === false ? (0, formatLabels_1.toWords)(field.name, true) : field.label);
            const type = buildObjectType({
                payload,
                name: fullName,
                parentName: fullName,
                fields: field.fields,
                forceNullable,
            });
            return {
                ...objectTypeConfig,
                [field.name]: { type },
            };
        },
        blocks: (objectTypeConfig, field) => {
            const blockTypes = field.blocks.map((block) => {
                (0, buildBlockType_1.default)({
                    payload,
                    block,
                    forceNullable,
                });
                return payload.types.blockTypes[block.slug];
            });
            const fullName = (0, combineParentName_1.default)(parentName, field.label === false ? (0, formatLabels_1.toWords)(field.name, true) : field.label);
            const type = new graphql_1.GraphQLList(new graphql_1.GraphQLUnionType({
                name: fullName,
                types: blockTypes,
                resolveType: (data) => payload.types.blockTypes[data.blockType].name,
            }));
            return {
                ...objectTypeConfig,
                [field.name]: { type },
            };
        },
        row: (objectTypeConfig, field) => field.fields.reduce((objectTypeConfigWithRowFields, subField) => {
            const addSubField = fieldToSchemaMap[subField.type];
            return addSubField(objectTypeConfigWithRowFields, subField);
        }, objectTypeConfig),
        collapsible: (objectTypeConfig, field) => field.fields.reduce((objectTypeConfigWithCollapsibleFields, subField) => {
            const addSubField = fieldToSchemaMap[subField.type];
            return addSubField(objectTypeConfigWithCollapsibleFields, subField);
        }, objectTypeConfig),
        tabs: (objectTypeConfig, field) => field.tabs.reduce((tabSchema, tab) => {
            return {
                ...tabSchema,
                ...tab.fields.reduce((subFieldSchema, subField) => {
                    const addSubField = fieldToSchemaMap[subField.type];
                    return addSubField(subFieldSchema, subField);
                }, tabSchema),
            };
        }, objectTypeConfig),
    };
    const objectSchema = {
        name,
        fields: () => fields.reduce((objectTypeConfig, field) => {
            const fieldSchema = fieldToSchemaMap[field.type];
            if (typeof fieldSchema !== 'function') {
                return objectTypeConfig;
            }
            return {
                ...objectTypeConfig,
                ...fieldSchema(objectTypeConfig, field),
            };
        }, baseFields),
    };
    const newlyCreatedBlockType = new graphql_1.GraphQLObjectType(objectSchema);
    return newlyCreatedBlockType;
}
exports.default = buildObjectType;
//# sourceMappingURL=data:application/json;base64, 