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

export const getLogs = async (data: any) => {
    try {
        // clear all remaining logs ne to info.
        const checked =
            data.checked && data.checked[0] === "true" ? true : false || false;
        const logData = await db
            .select()
            .from(logs)
            .where(
                and(
                    gte(
                        logs.created_at,
                        sql.raw(`NOW() - INTERVAL '${data.hours ?? "4"} hours'`)
                    ),
                    inArray(logs.service, data.service),
                    inArray(logs.level, data.level),
                    eq(logs.checked, checked)
                )
            )
            .orderBy(desc(logs.created_at));

        return { success: true, message: "logs returned", data: logData };
    } catch (error) {
        console.log(error);
        createLog(
            "error",
            "lst",
            "logger",
            `There was an error deleteing server logs. ${error}`
        );
        return {
            success: false,
            message: "An error occured while trying to get the logs",
            error,
        };
    }
};
