import { Request, Response, NextFunction } from "express";
import mongoose from "mongoose";

const logSchema = new mongoose.Schema({
  tool_name: String,
  tool_slug: String,
  mode: String,
  lang: String,
  inputText: String,
  ip: String,
  timestamp: { type: Date, default: Date.now },
});

const LogModel =
  mongoose.models.RequestLog || mongoose.model("RequestLog", logSchema);

export async function logsMiddleware(
  req: Request,
  res: Response,
  next: NextFunction
) {
  try {
    console.log(req.body);
    const ip =
      (req.headers["x-forwarded-for"] as string) ||
      req.socket.remoteAddress ||
      "";

    await LogModel.create({
      tool_name: req.body.tool_name,
      tool_slug: req.body.tool_slug,
      mode: req.body.mode,
      lang: req.body.lang,
      inputText: req.body.inputText,
      ip,
    });

    next();
  } catch (error) {
    console.error("Error logging request:", error);
    next();
  }
}
