const db = require("../db");

function uploadPatientFile(req, res) {
  const patientId = req.params.id;
  console.log("📁 req.file:", req.file);
  console.log("📁 req.body:", req.body);

  if (!req.file) {
    req.session.flash = {
      type: "danger",
      message: "Keine Datei ausgewählt"
    };
    return res.redirect("/patients");
  }

  db.query(`
    INSERT INTO patient_files
    (
      patient_id,
      original_name,
      file_name,
      file_path,
      mime_type,
      uploaded_by
    )
    VALUES (?, ?, ?, ?, ?, ?)
    `,
    [
      patientId,
      req.file.originalname,   // 👈 Originaler Dateiname
      req.file.filename,       // 👈 Gespeicherter Name
      req.file.path,           // 👈 Pfad
      req.file.mimetype,       // 👈 MIME-Type
      req.session.user.id
    ],
    err => {
      if (err) {
        console.error(err);
        req.session.flash = {
          type: "danger",
          message: "Datei konnte nicht gespeichert werden"
        };
        return res.redirect("/patients");
      }

      req.session.flash = {
        type: "success",
        message: "📎 Datei erfolgreich hochgeladen"
      };

      res.redirect("/patients");
    }
  );
}

module.exports = { uploadPatientFile };
