import { GlobalsModel } from '../models/Globals.model';

export class GlobalsRepository {
  async update(setting: { [key: string]: any }, userId?: string) {
    await Promise.all(Object.entries(setting).map(async ([setting, value]) => {
      if (!!userId) {
        await GlobalsModel.findOneAndUpdate({ setting }, { value, userId }, { upsert: true });
      } else {
        await GlobalsModel.findOneAndUpdate({ setting }, { value }, { upsert: true });
      }
    }));
  }

  async getSetting(setting: string) {
    const settingsValues = await GlobalsModel.findOne({ setting }).lean();
    if (!settingsValues) {
      return null;
    }
    return { [setting]: settingsValues.value };
  }
}
