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

function addMedication(req, res) {
  const patientId = req.params.id;
  const returnTo = req.query.returnTo;

  const {
    medication_variant_id,
    dosage_instruction,
    start_date,
    end_date
  } = req.body;

  if (!medication_variant_id) {
    return res.send("Medikament fehlt");
  }

  db.query(
    `
    INSERT INTO patient_medications
    (patient_id, medication_variant_id, dosage_instruction, start_date, end_date)
    VALUES (?, ?, ?, ?, ?)
    `,
    [
      patientId,
      medication_variant_id,
      dosage_instruction || null,
      start_date || null,
      end_date || null
    ],
    err => {
      if (err) return res.send("Fehler beim Speichern der Medikation");

      if (returnTo === "overview") {
        return res.redirect(`/patients/${patientId}/overview`);
      }

      res.redirect(`/patients/${patientId}/medications`);
    }
  );
}

function endMedication(req, res) {
  const medicationId = req.params.id;
  const returnTo = req.query.returnTo;

  db.query(
    "SELECT patient_id FROM patient_medications WHERE id = ?",
    [medicationId],
    (err, results) => {
      if (err || results.length === 0) {
        return res.send("Medikation nicht gefunden");
      }

      const patientId = results[0].patient_id;

      db.query(
        "UPDATE patient_medications SET end_date = CURDATE() WHERE id = ?",
        [medicationId],
        err => {
          if (err) return res.send("Fehler beim Beenden der Medikation");

          if (returnTo === "overview") {
            return res.redirect(`/patients/${patientId}/overview`);
          }

          res.redirect(`/patients/${patientId}/medications`);
        }
      );
    }
  );
}

function deleteMedication(req, res) {
  const medicationId = req.params.id;
  const returnTo = req.query.returnTo;

  db.query(
    "SELECT patient_id FROM patient_medications WHERE id = ?",
    [medicationId],
    (err, results) => {
      if (err || results.length === 0) {
        return res.send("Medikation nicht gefunden");
      }

      const patientId = results[0].patient_id;

      db.query(
        "DELETE FROM patient_medications WHERE id = ?",
        [medicationId],
        err => {
          if (err) return res.send("Fehler beim Löschen der Medikation");

          if (returnTo === "overview") {
            return res.redirect(`/patients/${patientId}/overview`);
          }

          res.redirect(`/patients/${patientId}/medications`);
        }
      );
    }
  );
}

module.exports = {
  addMedication,
  endMedication,
  deleteMedication
};
