const prisma = require("./client")

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

function withDeletedFilter(where = {}, options = {}) {
  if (options.includeDeleted || Object.prototype.hasOwnProperty.call(where, "deletedAt")) {
    return where
  }
  return { AND: [where, { deletedAt: null }] }
}

async function findComments(where, options = {}) {
  return prisma.comment.findMany({
    where: withDeletedFilter(where, options),
    include: options.include || undefined,
    select: options.select || undefined,
    orderBy: options.orderBy || { createdAt: "desc" },
    skip: Number.isInteger(options.skip) ? options.skip : undefined,
    take: Number.isInteger(options.take) ? options.take : undefined,
  })
}

async function findComment(where, options = {}) {
  return prisma.comment.findFirst({
    where: withDeletedFilter(where, options),
    include: options.include || undefined,
    select: options.select || undefined,
    orderBy: options.orderBy || { createdAt: "desc" },
  })
}
async function createComment(data, options = {}, db) {
  const p = getDb(db)
  return p.comment.create({
    data,
    include: options.include || undefined,
    select: options.select || undefined,
  })
}

async function deleteComment(where, db) {
  const p = getDb(db)
  return p.comment.delete({ where })
}

async function softDeleteComment(where, db) {
  const p = getDb(db)
  return p.comment.updateMany({ where, data: { deletedAt: new Date() } })
}
async function countComments(where = {}, db, options = {}) {
  const p = getDb(db)
  return p.comment.count({ where: withDeletedFilter(where, options) })
}


module.exports = {
  findComments,
  countComments,
  createComment,
  deleteComment,
  softDeleteComment,
  findComment
}
