// This will help maintain the server db so when we run an update it will show up here all the time.
// kinda bad too but this will help us keep the db identical.

import { db } from "../../../../database/dbclient.js";
import { serverData } from "../../../../database/schema/serverData.js";
import { createLog } from "../../logger/logger.js";
import fs from "fs";

export const serversCheckPoint = async () => {
    let servers: any[] = [];
    let filePath: string;
    if (process.env.NODE_ENV === "development") {
        filePath = "./server/services/server/utils/serverData.json";
    } else {
        filePath = "./dist/server/services/server/utils/serverData.json";
    }

    try {
        const data = fs.readFileSync(filePath, "utf8");
        const serverData = JSON.parse(data);
        servers = serverData.servers;
    } catch (err) {
        createLog(
            "error",
            "server",
            "server",
            `Error reading JSON file: ${JSON.stringify(err)}`
        );
    }

    // get the roles

    try {
        for (let i = 0; i < servers.length; i++) {
            const serverUpdate = await db
                .insert(serverData)
                .values(servers[i])
                .onConflictDoUpdate({
                    target: serverData.plantToken,
                    set: {
                        sName: servers[i].sName,
                        serverDNS: servers[i].serverDNS,
                        active: servers[i].active,
                        contactEmail: servers[i].contactEmail,
                        contactPhone: servers[i].contactPhone,
                        shippingHours: servers[i].shippingHours,
                        customerTiAcc: servers[i].customerTiAcc,
                        streetAddress: servers[i].streetAddress,
                        cityState: servers[i].cityState,
                        serverLoc: servers[i].serverLoc,
                        lstServerPort: servers[i].lstServerPort,
                        oldVersion: servers[i].oldVersion,
                        tiPostTime: servers[i].tiPostTime,
                        otherSettings: servers[i].otherSettings,
                    },
                }) // this will  only update the ones that are new :D
                .returning({ name: serverData.sName });
        }
        createLog(
            "info",
            "lst",
            "server",
            "Servers were just added/updated due to server startup"
        );
    } catch (error) {
        createLog(
            "error",
            "lst",
            "server",
            `There was an error adding/updating serverData to the db, ${error}`
        );
    }
};
