'use strict';

const { getDb, getSetting } = require('../db/database');

const USER_SETTING_KEYS = [
  'currency',
  'date_format',
  'grace_period_days',
  'notify_days_before',
];

function defaultUserSettings() {
  const defaults = {};
  for (const key of USER_SETTING_KEYS) {
    defaults[key] = getSetting(key);
  }
  return defaults;
}

function getUserSettings(userId) {
  const db = getDb();
  const settings = defaultUserSettings();
  const rows = db.prepare(`
    SELECT key, value
    FROM user_settings
    WHERE user_id = ?
  `).all(userId);

  for (const row of rows) {
    if (USER_SETTING_KEYS.includes(row.key)) settings[row.key] = row.value;
  }

  return settings;
}

function setUserSettings(userId, data) {
  const db = getDb();
  const upsert = db.prepare(`
    INSERT INTO user_settings (user_id, key, value, updated_at)
    VALUES (?, ?, ?, datetime('now'))
    ON CONFLICT(user_id, key) DO UPDATE SET
      value = excluded.value,
      updated_at = datetime('now')
  `);

  const save = db.transaction(() => {
    for (const [key, value] of Object.entries(data || {})) {
      if (USER_SETTING_KEYS.includes(key)) {
        upsert.run(userId, key, String(value));
      }
    }
  });

  save();
  return getUserSettings(userId);
}

module.exports = {
  USER_SETTING_KEYS,
  getUserSettings,
  setUserSettings,
};
