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

async function getPendingDeals({ page = 1, limit = 10, filters = {}, viewer = null } = {}) {
  return dealService.getDeals({
    preset: "RAW",
    q: filters?.q,
    page,
    limit,
    viewer,
    scope: "MOD",
    baseWhere: { status: "PENDING" },
    filters,
  })
}

async function updateDealStatus(dealId, nextStatus) {
  const id = Number(dealId)
  if (!Number.isInteger(id) || id <= 0) {
    const err = new Error("INVALID_DEAL_ID")
    err.statusCode = 400
    throw err
  }

  const deal = await dealDB.findDeal({ id }, { select: { id: true, status: true } })
  if (!deal) {
    const err = new Error("DEAL_NOT_FOUND")
    err.statusCode = 404
    throw err
  }

  if (deal.status === nextStatus) return { id: deal.id, status: deal.status }

  const updated = await dealDB.updateDeal(
    { id },
    { status: nextStatus },
    { select: { id: true, status: true } }
  )

  return updated
}

async function approveDeal(dealId) {
  return updateDealStatus(dealId, "ACTIVE")
}

async function rejectDeal(dealId) {
  return updateDealStatus(dealId, "REJECTED")
}

async function expireDeal(dealId) {
  return updateDealStatus(dealId, "EXPIRED")
}

async function unexpireDeal(dealId) {
  return updateDealStatus(dealId, "ACTIVE")
}

module.exports = {
  getPendingDeals,
  approveDeal,
  rejectDeal,
  expireDeal,
  unexpireDeal,
}
