import { DSQL_FieldSchemaType } from "../../types";
import serverError from "./serverError";

type Param = {
    data?: { [s: string]: any };
    fields?: string[];
    excludeData?: { [s: string]: any };
    excludeFields?: DSQL_FieldSchemaType[];
};

/**
 * # Add User Table to Database
 */
export default function grabSchemaFieldsFromData({
    data,
    fields,
    excludeData,
    excludeFields,
}: Param): DSQL_FieldSchemaType[] {
    try {
        /** @type {DSQL_FieldSchemaType[]} */
        const finalFields: DSQL_FieldSchemaType[] = [];

        /** @type {string[]} */
        let filteredFields: string[] = [];

        if (data && Object.keys(data)?.[0]) {
            filteredFields = Object.keys(data);
        }

        if (fields) {
            filteredFields = [...filteredFields, ...fields];
            filteredFields = [...new Set(filteredFields)];
        }

        filteredFields = filteredFields
            .filter(
                (fld) => !excludeData || !Object.keys(excludeData).includes(fld)
            )
            .filter(
                (fld) =>
                    !excludeFields ||
                    !excludeFields.find((exlFld) => exlFld.fieldName == fld)
            );

        filteredFields.forEach((fld) => {
            const value = data ? data[fld] : null;

            if (typeof value == "string") {
                const newField: DSQL_FieldSchemaType = {
                    fieldName: fld,
                    dataType: value.length > 255 ? "TEXT" : "VARCHAR(255)",
                };

                if (Boolean(value.match(/<[^>]+>/g))) {
                    newField.richText = true;
                }

                finalFields.push(newField);
            } else if (typeof value == "number") {
                finalFields.push({
                    fieldName: fld,
                    dataType: "INT",
                });
            } else {
                finalFields.push({
                    fieldName: fld,
                    dataType: "VARCHAR(255)",
                });
            }
        });

        return finalFields;
    } catch (/** @type {any} */ error: any) {
        console.log(`grabSchemaFieldsFromData.ts ERROR: ${error.message}`);

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

        return [];
    }
}
