import StoreSettings from '../models/StoreSettings.js';

const backfillDefaults = async (settings) => {
  let dirty = false;
  for (const [path, schemaType] of Object.entries(settings.schema.paths)) {
    if (path === '_id' || path === '__v' || path.includes('._id')) continue;
    if (schemaType.defaultValue === undefined) continue;
    const current = settings.get(path);
    if (current === undefined || current === null) {
      settings.set(
        path,
        typeof schemaType.defaultValue === 'function'
          ? schemaType.defaultValue()
          : schemaType.defaultValue
      );
      dirty = true;
    }
  }
  if (dirty) await settings.save();
};

export const getSettings = async () => {
  let settings = await StoreSettings.findOne();
  if (!settings) {
    settings = await StoreSettings.create({});
  } else {
    await backfillDefaults(settings);
  }
  return settings;
};

export const updateSettings = async (data) => {
  let settings = await StoreSettings.findOne();
  if (settings) {
    Object.assign(settings, data);
    await settings.save();
  } else {
    settings = await StoreSettings.create(data);
  }
  return settings;
};
