import createDbFromSchema from "@/package-shared/shell/createDbFromSchema";
import grabDirNames from "@/package-shared/utils/backend/names/grab-dir-names";
import debugLog from "@/package-shared/utils/logging/debug-log";
import dbSchemaToType from "@/utils/backend/db-schema-to-type";
import fs from "fs";

function debugLogFn(log: any, label?: string) {
    debugLog({ log, addTime: true, label, title: "watchMainDbSchemaJSONFile" });
}

let syncing = 0;
let timeout: any;

const DEBOUNCE = 500;

export default function watchMainDbSchemaJSONFile() {
    if (process.env.NODE_ENV?.match(/prod/)) return;
    if (process.env.DSQL_HOST_ENV?.match(/prod/)) return;

    const { mainShemaJSONFilePath, mainDbTypeDefFile } = grabDirNames();

    fs.watch(mainShemaJSONFilePath, (curr) => {
        if (syncing == 1) return;
        if (curr !== "change") return;
        clearTimeout(timeout);

        debugLogFn("Main Schema JSON File Changed!");

        syncing = 1;

        timeout = setTimeout(() => {
            const definitions = dbSchemaToType();

            fs.writeFileSync(
                mainDbTypeDefFile,
                definitions?.join("\n\n") || "",
                "utf-8"
            );

            createDbFromSchema({})
                .then((res) => {
                    debugLogFn(res, "res");
                })
                .catch((err) => {
                    debugLogFn(err, "res");
                })
                .finally(() => {
                    setTimeout(() => {
                        debugLogFn("Main Rebuilt Successfully!");
                        syncing = 0;
                    }, 1000);
                });
        }, DEBOUNCE);
    });
}
