const categoryDb = require("../db/category.db")
const dealService = require("./deal.service")

async function findCategoryBySlug(slug) {
  const normalizedSlug = String(slug || "").trim()
  if (!normalizedSlug) {
    throw new Error("INVALID_SLUG")
  }

  const category = await categoryDb.findCategoryBySlug(normalizedSlug)
  if (!category) {
    throw new Error("CATEGORY_NOT_FOUND")
  }

  const breadcrumb = await categoryDb.getCategoryBreadcrumb(category.id)
  return { category, breadcrumb }
}

async function getDealsByCategoryId(categoryId, { page = 1, limit = 10, filters = {}, viewer = null, scope = "USER" } = {}) {
  const normalizedId = Number(categoryId)
  if (!Number.isInteger(normalizedId) || normalizedId <= 0) {
    throw new Error("INVALID_CATEGORY_ID")
  }

  const categoryIds = await categoryDb.getCategoryDescendantIds(normalizedId)

  return dealService.getDeals({
    preset: "NEW",
    q: filters?.q,
    page,
    limit,
    viewer,
    scope,
    baseWhere: { categoryId: { in: categoryIds } },
    filters,
  })
}

module.exports = {
  findCategoryBySlug,
  getDealsByCategoryId,
}
