const prisma = require("./client")

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

async function upsertDealSave({ userId, dealId, createdAt }, db) {
  const p = getDb(db)
  return p.dealSave.upsert({
    where: { userId_dealId: { userId, dealId } },
    update: {},
    create: {
      userId,
      dealId,
      createdAt: createdAt ?? undefined,
    },
  })
}

async function deleteDealSave({ userId, dealId }, db) {
  const p = getDb(db)
  return p.dealSave.delete({
    where: { userId_dealId: { userId, dealId } },
  })
}

async function findDealSavesByUser(
  userId,
  { skip = 0, take = 20, include, orderBy, where } = {},
  db
) {
  const p = getDb(db)
  return p.dealSave.findMany({
    where: where || { userId },
    include: include || undefined,
    orderBy: orderBy || { createdAt: "desc" },
    skip,
    take,
  })
}

async function countDealSavesByUser(userId, { where } = {}, db) {
  const p = getDb(db)
  return p.dealSave.count({ where: where || { userId } })
}

module.exports = {
  upsertDealSave,
  deleteDealSave,
  findDealSavesByUser,
  countDealSavesByUser,
}
