const prisma = require("./client")

function getDb(db) {
  return db || prisma
}

async function createUserNote({ userId, createdById, note }, db) {
  const p = getDb(db)
  return p.userNote.create({
    data: {
      userId,
      createdById,
      note,
    },
  })
}

async function listUserNotes({ userId, skip = 0, take = 20 }, db) {
  const p = getDb(db)
  return p.userNote.findMany({
    where: { userId },
    orderBy: { createdAt: "desc" },
    skip,
    take,
    include: { createdBy: { select: { id: true, username: true } } },
  })
}

async function countUserNotes(where = {}, db) {
  const p = getDb(db)
  return p.userNote.count({ where })
}

module.exports = {
  createUserNote,
  listUserNotes,
  countUserNotes,
}
