import fs from "fs";
import { EJSON } from "@/client-exports";
import grabDirNames from "@/package-shared/utils/backend/names/grab-dir-names";
import {
    DSQL_DatabaseSchemaType,
    DSQL_FieldSchemaType,
    DSQL_TableSchemaType,
} from "@/package-shared/types";
import generateTypeDefinition from "@/components/admin/databases/functions/generateTypeDefinition";
import _ from "lodash";

export default function dbSchemaToType(): string[] | undefined {
    const { mainShemaJSONFilePath, defaultTableFieldsJSONFilePath } =
        grabDirNames();

    const mainSchema = EJSON.parse(
        fs.readFileSync(mainShemaJSONFilePath, "utf-8")
    ) as DSQL_DatabaseSchemaType[];

    const datasquirelSchema = mainSchema.find(
        (sch) => sch.dbFullName == "datasquirel"
    );

    if (!datasquirelSchema) return;

    let tableNames = `export const DsqlTables = [\n${datasquirelSchema.tables
        .map((tbl) => `    "${tbl.tableName}",`)
        .join("\n")}\n] as const`;

    const defaultFields = EJSON.parse(
        fs.readFileSync(defaultTableFieldsJSONFilePath, "utf-8")
    ) as DSQL_FieldSchemaType[];

    const dbTablesSchemas = datasquirelSchema.tables.map((tblSchm) => {
        let newDefaultFields = _.cloneDeep(defaultFields);
        return {
            ...tblSchm,
            fields: [
                newDefaultFields.shift(),
                newDefaultFields.shift(),
                ...tblSchm.fields,
                ...newDefaultFields,
            ],
        } as DSQL_TableSchemaType;
    });

    const schemas = dbTablesSchemas
        .map((table) =>
            generateTypeDefinition({
                paradigm: "TypeScript",
                table,
                typeDefName: `DSQL_DATASQUIREL_${table.tableName.toUpperCase()}`,
                allValuesOptional: true,
                addExport: true,
            })
        )
        .filter((schm) => typeof schm == "string");

    return [tableNames, ...schemas];
}
