const fs = require('fs');
const db = require('../../models/migration');
const BugReporting = db.BugReporting;
const onFinished = require('on-finished');

// Fungsi untuk menyimpan bug report ke database
async function saveBugReport(report) {
  try {
    const bugReport = await BugReporting.create(report);
    return bugReport.insertId;
  } catch (error) {
    console.error('Error while saving bug report to database:', error);
    throw error;
  }
}

function errorHandler(err, req, res) {
  // console.error('Error :', err);
  // console.error('request :', req);
  // console.error('Response :', res);

  const bugReport = {
    class: err.constructor.name,
    file: err.fileName || null,
    code: null,
    status_code: res.statusCode || null,
    line: err.lineNumber || null,
    message: err.message,
    trace: err.stack,
    user_id: null,
    data: JSON.stringify(req.body),
    url: req.originalUrl,
    method: req.method,
    ip: req.ip,
    created_at: new Date(),
    updated_at: new Date(),
  };

  // Simpan bug report ke database
  saveBugReport(bugReport)
    .then(() => {
      // Tangani respons kesalahan
      console.error('error: Terjadi kesalahan dalam server');
    })
    .catch((error) => {
      console.error('Error while saving bug report:', error);
    });
}

module.exports = errorHandler;
