import {db} from "../../../database/dbclient.js";
import {logs} from "../../../database/schema/logs.js";
import build from "pino-abstract-transport";

type Log = {
    username: string | null;
    service: string;
    level: string;
    msg: string;
};

const pinoLogLevels: any = {
    10: "trace",
    20: "debug",
    30: "info",
    40: "warn",
    50: "error",
    60: "fatal",
};
// Create a custom transport function
export default async function (log: Log) {
    //const {username, service, level, msg, ...extra} = log;
    try {
        return build(async function (source) {
            for await (let obj of source) {
                // Insert log entry into the PostgreSQL database using Drizzle ORM

                // convert to the name to make it more easy to find later :P
                const levelName = pinoLogLevels[obj.level] || "unknown";
                await db.insert(logs).values({
                    level: levelName,
                    username: obj?.username.toLowerCase(),
                    service: obj?.service.toLowerCase(),
                    message: obj.msg,
                });
            }
        });
    } catch (err) {
        console.error("Error inserting log into database:", err);
    }
}
