// db/dealAiReview.db.js
const prisma = require("./client")

async function upsertDealAiReview(dealId, input = {}) {
  const data = {
    bestCategoryId: input.bestCategoryId ?? input.best_category_id ?? 0,
    needsReview: Boolean(input.needsReview ?? input.needs_review ?? false),
    hasIssue: Boolean(input.hasIssue ?? input.has_issue ?? false),
    issueType: (input.issueType ?? input.issue_type ?? "NONE"),
    issueReason: input.issueReason ?? input.issue_reason ?? null,
  }

  return prisma.dealAiReview.upsert({
    where: { dealId },
    update: data,
    create: { dealId, ...data },
  })
}

async function findDealAiReviewByDealId(dealId, options = {}) {
  return prisma.dealAiReview.findUnique({
    where: { dealId },
    select: options.select || undefined,
    include: options.include || undefined,
  })
}

async function deleteDealAiReviewByDealId(dealId) {
  return prisma.dealAiReview.delete({
    where: { dealId },
  })
}

async function listDealsNeedingAiReview({ page = 1, limit = 50 } = {}) {
  const take = Math.min(Math.max(Number(limit) || 50, 1), 200)
  const skip = (Math.max(Number(page) || 1, 1) - 1) * take

  const where = {
    OR: [{ needsReview: true }, { hasIssue: true }],
  }

  const [items, total] = await Promise.all([
    prisma.dealAiReview.findMany({
      where,
      orderBy: [{ updatedAt: "desc" }],
      skip,
      take,
      include: {
        deal: {
          select: {
            id: true,
            title: true,
            url: true,
            status: true,
            createdAt: true,
            userId: true,
            categoryId: true,
            sellerId: true,
          },
        },
      },
    }),
    prisma.dealAiReview.count({ where }),
  ])

  return { items, total, page: Math.max(Number(page) || 1, 1), limit: take }
}

module.exports = {
  upsertDealAiReview,
  findDealAiReviewByDealId,
  deleteDealAiReviewByDealId,
  listDealsNeedingAiReview,
}
