import { PrismaClient } from '@prisma/client';
import build from 'pino-abstract-transport';

const prisma = new PrismaClient();

export default async function(opts)
{
  return build(async(source) =>
  {
    for await (const obj of source)
    {
      try
      {
        const { time, level, msg, ...meta } = obj;
        // Pino levels are numeric, convert to string names if needed
        const levelMap = {
          '10': 'trace',
          '20': 'debug',
          '30': 'info',
          '40': 'warn',
          '50': 'error',
          '60': 'fatal'
        };
        const levelString = levelMap[level] || 'info'; // Default to info

        await prisma.log.create({
          data: {
            timestamp: new Date(time),
            level: levelString,
            message: msg,
            // Store remaining properties in the meta field if it exists
            meta: Object.keys(meta).length > 0 ? meta : undefined,
          },
        });
      }
      catch (error)
      {
        console.error('Failed to write log to database:', error);
      }
    }
  }, {
    async close(err)
    {
      await prisma.$disconnect();
    }
  });
}
