const prisma = require("./client") // Prisma client

/**
 * Kategoriyi slug'a gore bul
 */
async function findCategoryBySlug(slug, options = {}) {
  const s = String(slug ?? "").trim().toLowerCase()
  return prisma.category.findUnique({
    where: { slug: s },
    select: options.select || undefined,
    include: options.include || undefined,
  })
}

/**
 * Kategorinin firsatlarini al
 * Sayfalama ve filtreler ile firsatlari cekiyoruz
 */
async function listCategoryDeals({ where = {}, skip = 0, take = 10 }) {
  return prisma.deal.findMany({
    where,
    skip,
    take,
    orderBy: { createdAt: "desc" },
  })
}

async function getCategoryDescendantIds(categoryId) {
  const rootId = Number(categoryId)
  if (!Number.isInteger(rootId) || rootId <= 0) {
    throw new Error("categoryId must be int")
  }

  const seen = new Set([rootId])
  let queue = [rootId]

  while (queue.length > 0) {
    const children = await prisma.category.findMany({
      where: { parentId: { in: queue } },
      select: { id: true },
    })

    const next = []
    for (const child of children) {
      if (!seen.has(child.id)) {
        seen.add(child.id)
        next.push(child.id)
      }
    }
    queue = next
  }

  return Array.from(seen)
}

async function getCategoryBreadcrumb(categoryId, { includeUndefined = false } = {}) {
  let currentId = Number(categoryId)
  if (!Number.isInteger(currentId)) throw new Error("categoryId must be int")

  const path = []
  const visited = new Set()

  while (true) {
    if (visited.has(currentId)) break
    visited.add(currentId)

    const cat = await prisma.category.findUnique({
      where: { id: currentId },
      select: { id: true, name: true, slug: true, parentId: true },
    })

    if (!cat) break

    if (includeUndefined || cat.id !== 0) {
      path.push({ id: cat.id, name: cat.name, slug: cat.slug })
    }

    if (cat.parentId === null || cat.parentId === undefined) break
    currentId = cat.parentId
  }

  return path.reverse()
}

module.exports = {
  getCategoryBreadcrumb,
  findCategoryBySlug,
  listCategoryDeals,
  getCategoryDescendantIds,
}
