const { Worker } = require("bullmq")
const { connection } = require("../jobs/dealClassification.queue")
const dealDB = require("../db/deal.db")
const dealAiReviewDb = require("../db/dealAiReview.db")
const { classifyDeal } = require("../services/dealClassification.service")

async function handler(job) {
  const { dealId } = job.data
  if (!dealId) throw new Error("dealId missing")

const deal = await dealDB.findDeal(
  { id: Number(dealId) },
  {
    select: {
      id: true,
      title: true,
      description: true,
      url: true,
      seller: { select: { name: true } },
    },
  }
)
  if (!deal) throw new Error(`Deal not found: ${dealId}`)

  const ai = await classifyDeal({
    title: deal.title,
    description: deal.description,
    url: deal.url,
    seller: deal.seller?.name ?? null,
  })

  await dealAiReviewDb.upsertDealAiReview(deal.id, {
    best_category_id: ai.best_category_id,
    needs_review: ai.needs_review,
    has_issue: ai.has_issue,
    issue_reason: ai.issue_reason,
    issue_type: ai.issue_type,
  })

  // İstersen auto-set (şimdilik dursun, id mismatch riskini biliyorsun)
  // if (!ai.needs_review && !ai.has_issue) {
  //   await dealDB.updateDealById(deal.id, { categoryId: ai.best_category_id })
  // }

  return { ok: true }
}

function startDealClassificationWorker() {
  const worker = new Worker("deal-classification", handler, {
    connection,
    concurrency: 5,
  })

  worker.on("completed", (job) => console.log("✅ job completed", job.id))
  worker.on("failed", (job, err) => console.error("❌ job failed", job?.id, err?.message))

  return worker
}

module.exports = { startDealClassificationWorker }
