process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0";
import axios from "axios";
import { pino } from "pino";
import build from "pino-abstract-transport";
import { tryCatch } from "../../globalUtils/tryCatch.js";

const pinoLogLevels: any = {
    10: "trace",
    20: "debug",
    30: "info",
    40: "warn",
    50: "error",
    60: "fatal",
};

export default async function buildGoTransport() {
    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,
                // });
                const { data, error } = (await tryCatch(
                    axios.post(`${process.env.LST_BASE_URL}/api/v1/log`, {
                        service: obj?.service.toLowerCase(),
                        level: levelName,
                        message: obj.msg,
                    })
                )) as any;

                if (error) {
                    console.log(
                        "The go server must be offline so we cant post the new logs."
                    );
                }

                // console.log(`Go log level: ${levelName}`);
            }
        });
    } catch (err) {
        console.error("Error inserting log into database:", err);
    }
}
