const configs = require("../configs");
const DeviceModel = require("../models/device.model");

const save = async (
  token,
  device_name,
  device_type,
  manifactor,
  serial_number,
  model,
  firmware_version,
  device_ip_address,
  sensor_value,
  battery_life
) => {
  if (token === configs.verifyToken) {
    try {
      // Önce kaydı bulalım
      const existingDevice = await DeviceModel.findOne({
        device_name,
        device_type,
        manifactor,
        serial_number,
        model,
        firmware_version
      });
      if (!existingDevice) {
        // İlk defa kaydet
        const newDevice = new DeviceModel({
          device_name,
          device_type,
          manifactor,
          serial_number,
          model,
          firmware_version,
          device_ip_address,
          update_time: new Date(Date.now()),
          device_log: {
            sensor_value,
            battery_life
          }
        });
        const result = await newDevice.save();
        return "Cihaz kaydedildi.";
      } else {
        // Daha önce kaydedilmiş ise sadece ip adresini güncelle
        const filter = {
          device_name,
          device_type,
          manifactor,
          serial_number,
          model,
          firmware_version
        };

        let update;

        if (sensor_value === undefined && battery_life === undefined) {
          update = {
            $set: {
              device_ip_address,
              update_time: new Date(Date.now()),
            }
          };
        } else {
          update = {
            $set: {
              device_ip_address,
              update_time: new Date(Date.now()),
              device_log: {
                sensor_value,
                battery_life
              }
            }
          };
        }

        const result = await DeviceModel.updateOne(filter, update);

        if (result.nModified === 0) {
          throw new Error("Güncellenmek istenen kayıt bulunamadı");
        }

        return "IP Adresi güncellendi";
      }
    } catch (error) {
      throw new Error("Mongodb: " + error.message + " (save.controller)");
    }
  } else {
    throw new Error("Hatalı token (save.controller)");
  }
};

module.exports = { save };
