import { and, eq, inArray, lte, ne, sql } from "drizzle-orm";
import { db } from "../../../../database/dbclient.js";
import { logs } from "../../../../database/schema/logs.js";
import { createLog } from "../logger.js";

export const logCleanup = async () => {
    /**
     * We will run the clean logger where we have aged logs that do not need to be here flooding the db
     */

    // clear the server logs older than 3 days
    try {
        // clear info logs older than 3 days
        const delLogs = await db
            .delete(logs)
            .where(
                and(
                    lte(logs.created_at, sql`NOW() - INTERVAL '3 days'`),
                    //inArray(logs.service, ["server", "tcp", "sqlProd", "globalutils","notify", "logger", "serverupdater"]),
                    eq(logs.level, "info")
                )
            )
            .returning({ name: logs.message });
        createLog(
            "info",
            "lst",
            "logger",
            `${delLogs.length} Server logs were just deleted that were older than 3 days`
        );
    } catch (error) {
        createLog(
            "error",
            "lst",
            "logger",
            `There was an error deleteing server logs. ${error}`
        );
    }

    try {
        // clear all remaining logs ne to info.
        const delLogs = await db
            .delete(logs)
            .where(
                and(
                    lte(logs.created_at, sql`NOW() - INTERVAL '7 days'`),
                    //inArray(logs.service, ["server", "tcp", "sqlProd", "globalutils", "notify", "logger", "serverupdater"]),
                    ne(logs.level, "info")
                )
            )
            .returning({ name: logs.message });
        createLog(
            "info",
            "lst",
            "logger",
            `${delLogs.length} Server logs were just deleted that were older than 7 days`
        );
    } catch (error) {
        createLog(
            "error",
            "lst",
            "logger",
            `There was an error deleteing server logs. ${error}`
        );
    }
};
