import prisma from '../database.js';

export async function getSetting(key)
{
  const setting = await prisma.setting.findUnique({
    where: { key },
    select: { value: true }
  });

  console.log(`getSetting(${key})`, setting);

  return setting?.value ? JSON.parse(setting.value) : null;
}

export async function setSetting(key, value)
{
  //Replace all CRLFs with LF
  if (typeof value === 'string')
  {
    value = value.replace(/\r\n/g, '\n').trim();
  }

  await prisma.setting.upsert({
    where: { key },
    update: { value: JSON.stringify(value) },
    create: { key, value: JSON.stringify(value) }
  });
}

export async function getUserPreference(userId, key)
{
  const pref = await prisma.userPreference.findUnique({
    where: { userId_key: { userId, key } },
    select: { value: true }
  });
  return pref?.value ? JSON.parse(pref.value) : null;
}

export async function setUserPreference(userId, key, value)
{
  if (typeof value === 'string')
  {
    value = value.replace(/\r\n/g, '\n').trim();
  }
  await prisma.userPreference.upsert({
    where: { userId_key: { userId, key } },
    update: { value: JSON.stringify(value) },
    create: { userId, key, value: JSON.stringify(value) }
  });
}