const prisma = require("./client")

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

async function upsertDealReport({ dealId, userId, reason, note }, db) {
  const p = getDb(db)
  return p.dealReport.upsert({
    where: { dealId_userId: { dealId, userId } },
    update: {
      reason,
      note: note ?? null,
      status: "OPEN",
    },
    create: {
      dealId,
      userId,
      reason,
      note: note ?? null,
    },
  })
}

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

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

async function updateDealReportStatus(reportId, status, db) {
  const p = getDb(db)
  return p.dealReport.update({
    where: { id: Number(reportId) },
    data: { status },
  })
}

module.exports = {
  upsertDealReport,
  listDealReports,
  countDealReports,
  updateDealReportStatus,
}
