import { DSQL_FieldSchemaType, DSQL_TableSchemaType } from "../../types";
import grabSchemaFieldsFromData from "./grabSchemaFieldsFromData";
import serverError from "./serverError";

/**
 * # Add User Table to Database
 */
export default function grabNewUsersTableSchema(params: {
    payload?: { [s: string]: any };
}): DSQL_TableSchemaType | null {
    try {
        const userPreset: DSQL_TableSchemaType = require("../../data/presets/users.json");
        const defaultFields: DSQL_FieldSchemaType[] = 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: any) {
        console.log(`grabNewUsersTableSchema.ts ERROR: ${error.message}`);

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

        return null;
    }
}
