// services/seller/sellerService.js
const { findSeller } = require("../db/seller.db")
const dealService = require("./deal.service")

function normalizeSellerName(value) {
  return String(value || "").trim()
}

async function getSellerByName(name) {
  const normalized = normalizeSellerName(name)
  if (!normalized) {
    const err = new Error("SELLER_NAME_REQUIRED")
    err.statusCode = 400
    throw err
  }

  return findSeller(
    { name: { equals: normalized, mode: "insensitive" } },
    { select: { id: true, name: true, url: true, sellerLogo: true } }
  )
}

async function getDealsBySellerName(name, { page = 1, limit = 10, filters = {}, viewer = null, scope = "USER" } = {}) {
  const seller = await getSellerByName(name)
  if (!seller) {
    const err = new Error("SELLER_NOT_FOUND")
    err.statusCode = 404
    throw err
  }

  const payload = await dealService.getDeals({
    preset: "NEW",
    q: filters?.q,
    page,
    limit,
    viewer,
    scope,
    baseWhere: { sellerId: seller.id, status: "ACTIVE" },
    filters,
  })

  return { seller, payload }
}

module.exports = {
  getSellerByName,
  getDealsBySellerName,
}
