const express = require("express");
const categoryService = require("../services/category.service");  // Kategori servisi
const router = express.Router();
const optionalAuth = require("../middleware/optionalAuth")
const { mapCategoryToCategoryDetailsResponse }=require("../adapters/responses/categoryDetails.adapter")
const { mapDealToDealDetailResponse } = require("../adapters/responses/dealDetail.adapter")
const { mapPaginatedDealsToDealCardResponse } = require("../adapters/responses/dealCard.adapter")
const { getClientIp } = require("../utils/requestInfo")
const { queueDealImpressions } = require("../services/redis/dealAnalytics.service")


router.get("/:slug", async (req, res) => {
  const { slug } = req.params;  // URL parametresinden slug alıyoruz
  try {

    const { category, breadcrumb } = await categoryService.findCategoryBySlug(slug);  // Servisten kategori ve breadcrumb bilgilerini alıyoruz
    if (!category) {
      return res.status(404).json({ error: "Kategori bulunamadı" });
    }
    const response = mapCategoryToCategoryDetailsResponse(category, breadcrumb);  // Adapter ile veriyi dönüştürüyoruz
    res.json(response);
  } catch (err) {
    res.status(500).json({ error: "Kategori detayları alınırken bir hata oluştu", message: err.message });
  }
});


const buildViewer = (req) =>
  req.auth ? { userId: req.auth.userId, role: req.auth.role } : null

router.get("/:slug/deals", optionalAuth, async (req, res) => {
  const { slug } = req.params; 
  const { page = 1, limit = 10, ...filters } = req.query;

  try {
    const { category } = await categoryService.findCategoryBySlug(slug); 
    if (!category) {
      return res.status(404).json({ error: "Kategori bulunamadı" });
    }

    // Kategorinin fırsatlarını alıyoruz
    const payload = await categoryService.getDealsByCategoryId(category.id, {
      page,
      limit,
      filters,
      viewer: buildViewer(req),
    });  

    const response = mapPaginatedDealsToDealCardResponse(payload)
    const dealIds = payload?.results?.map((deal) => deal.id) || []
    queueDealImpressions({
      dealIds,
      userId: req.auth?.userId ?? null,
      ip: getClientIp(req),
    }).catch((err) => console.error("Deal impression queue failed:", err?.message || err))
    

    res.json({
      page: response.page,
      total: response.total,
      totalPages: response.totalPages,
      results: response.results,
      minPrice: payload?.minPrice ?? null,
      maxPrice: payload?.maxPrice ?? null,
    })
  } catch (err) {
    res.status(500).json({ error: "Kategoriye ait fırsatlar alınırken bir hata oluştu", message: err.message });
  }
});


module.exports = router;
