const mongoose = require('mongoose');
const { Schema } = mongoose;

const systemSettingSchema = new Schema({
  _id: {
    type: String,
    default: 'system' // 固定 ID
  },
  innerDefaultAmount: {
    type: Number,
    required: true,
    default: 10000
  },
  minProfitAmount: {
    type: Number,
    required: true,
    default: 0
  },
  innerRebateRatio: {
    type: Number,
    required: true,
    default: 0
  },
  obRebateRatio: {
    type: Number,
    required: true,
    default: 0
  },
  hgRebateRatio: {
    type: Number,
    required: true,
    default: 0
  },
  runWorkerEnabled: {
    type: Boolean,
    required: true,
    default: false
  }
}, {
  toJSON: {
    transform(doc, ret) {
      delete ret._id;
      delete ret.__v;
    }
  },
  toObject: {
    transform(doc, ret) {
      delete ret._id;
      delete ret.__v;
    }
  }
});

const Setting = mongoose.model('SystemSetting', systemSettingSchema);
const CALLBACKS = {
  update: null,
};

const onUpdate = (callback) => {
  CALLBACKS.update = callback;
}

const get = async () => {
  return await Setting.findById('system');
}

const update = async (fields) => {
  CALLBACKS.update?.(fields);
  return await Setting.findByIdAndUpdate(
    'system',
    { $set: fields },
    { upsert: true, new: true }
  );
}

const init = async (fields = {}) => {
  const systemSetting = await Setting.findById('system');
  if (systemSetting) {
    return;
  }
  const setting = new Setting({
    _id: 'system',
    ...fields,
  });
  return setting.save();
}

module.exports = { get, update, init, onUpdate };