/**
 * @copyright 2026 NHCarrigan
 * @license Naomi's Public License
 * @author Naomi Carrigan
 */

import { FastifyInstance, FastifyRequest } from 'fastify';
import { logger } from '../../utils/logger';

interface LogBody {
  level: 'debug' | 'info' | 'warn' | 'error';
  message: string;
  context?: string;
  error?: {
    name: string;
    message: string;
    stack?: string;
  };
}

export default async function (fastify: FastifyInstance) {
  fastify.post('/', async function (request: FastifyRequest<{ Body: LogBody }>) {
    const { level, message, context, error } = request.body;

    if (level === 'error' && error) {
      const errorObj = new Error(error.message);
      errorObj.name = error.name;
      if (error.stack) {
        errorObj.stack = error.stack;
      }
      await logger.error(context || 'Frontend', errorObj);
    } else if (level === 'error') {
      await logger.error('Frontend', new Error(message));
    } else {
      const logMessage = context ? `[${context}] ${message}` : message;
      await logger.log(level, logMessage);
    }

    return { success: true };
  });
}
