const { json, now, one, parseJson, run } = require('../db');
const { publicUser } = require('../middleware/auth');
const { capabilitiesForRole } = require('./roles');

const defaultPreferences = {
  theme: 'depreCoreDark'
};

function getPreferences(userId) {
  const row = one('SELECT preferences_json FROM user_preferences WHERE user_id = ?', [userId]);
  return {
    ...defaultPreferences,
    ...parseJson(row?.preferences_json, {})
  };
}

function getProfile(user) {
  return {
    user: publicUser(user),
    preferences: getPreferences(user.id),
    capabilities: capabilitiesForRole(user.role)
  };
}

function savePreferences(userId, preferences) {
  const merged = {
    ...getPreferences(userId),
    ...(preferences || {})
  };
  run(
    `INSERT INTO user_preferences (user_id, preferences_json, updated_at)
     VALUES (?, ?, ?)
     ON CONFLICT(user_id) DO UPDATE SET
       preferences_json = excluded.preferences_json,
       updated_at = excluded.updated_at`,
    [userId, json(merged), now()]
  );
  return merged;
}

module.exports = {
  defaultPreferences,
  getProfile,
  getPreferences,
  savePreferences
};
