const { Worker } = require("bullmq")
const { connection } = require("../jobs/dealClassification.queue")
const { classifyDeal } = require("../services/dealClassification.service")
const { getDealFromRedis, updateDealInRedis } = require("../services/redis/dealCache.service")
const { queueDealAiReviewUpdate } = require("../services/redis/dbSync.service")
const { getSellerById } = require("../services/redis/sellerCache.service")
const dealDB = require("../db/deal.db")

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

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

  let sellerName = deal?.seller?.name ?? null
  if (!sellerName && deal?.sellerId) {
    const seller = await getSellerById(Number(deal.sellerId))
    sellerName = seller?.name ?? null
  }
  if (!sellerName && deal?.customSeller) sellerName = deal.customSeller

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

  const aiReview = {
    bestCategoryId: ai.best_category_id,
    tags: ai.tags || [],
    needsReview: ai.needs_review,
    hasIssue: ai.has_issue,
    issueReason: ai.issue_reason,
    issueType: ai.issue_type,
  }

  await updateDealInRedis(deal.id, { aiReview }, { updatedAt: new Date() })
  queueDealAiReviewUpdate({
    dealId: deal.id,
    data: aiReview,
    updatedAt: new Date().toISOString(),
  }).catch((err) => console.error("DB sync deal aiReview failed:", err?.message || err))

  // İ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 }
