// @ts-check

const grabSchemaFieldsFromData = require("./grabSchemaFieldsFromData");
const serverError = require("./serverError");

/**
 * # Add User Table to Database
 *
 * @param {object} [params]
 * @param {Object<string,any>} [params.payload] - fields to add to the table
 *
 * @returns {import("../../types").DSQL_TableSchemaType | null} new user auth object payload
 */
module.exports = function grabNewUsersTableSchema(params) {
    try {
        /** @type {import("../../types").DSQL_TableSchemaType} */
        const userPreset = require("../../data/presets/users.json");
        /** @type {import("../../types").DSQL_FieldSchemaType[]} */
        const defaultFields = require("../../data/defaultFields.json");

        const supplementalFields = params?.payload
            ? grabSchemaFieldsFromData({
                  data: params?.payload,
                  excludeData: defaultFields,
                  excludeFields: userPreset.fields,
              })
            : [];

        console.log("supplementalFields", supplementalFields);

        const allFields = [...userPreset.fields, ...supplementalFields];

        console.log("allFields", allFields);

        const finalFields = [
            ...defaultFields.slice(0, 2),
            ...allFields,
            ...defaultFields.slice(2),
        ];

        userPreset.fields = [...finalFields];

        return userPreset;
    } catch (/** @type {any} */ error) {
        console.log(`grabNewUsersTableSchema.js ERROR: ${error.message}`);

        serverError({
            component: "grabNewUsersTableSchema",
            message: error.message,
        });

        return null;
    }
};
