const express = require("express")
const router = express.Router()
const { getDeals, getDealById, createDeal,searchDeals } = require("../services/deal.service")
const authRequiredMiddleware = require("../middleware/authRequired.middleware")
const authOptionalMiddleware = require("../middleware/authOptional.middleware")
const { upload } = require("../middleware/upload.middleware");


const {mapCreateDealRequestToDealCreateData} =require("../adapters/requests/dealCreate.adapter")
const { mapDealToDealDetailResponse } = require("../adapters/responses/dealDetail.adapter")
const { mapDealToDealCardResponse,mapPaginatedDealsToDealCardResponse } = require("../adapters/responses/dealCard.adapter")


router.get("/", authOptionalMiddleware, async (req, res) => {
  try {
    const q = (req.query.q ?? "").toString().trim()
    const page = Number(req.query.page) || 1
    const limit = Number(req.query.limit) || 10
    const userId = req.user?.userId ?? null
    const data = await getDeals({ q, page, limit, userId })
    
    res.json(mapPaginatedDealsToDealCardResponse(data))
  } catch (e) {
    console.error(e)
    res.status(500).json({ error: "Sunucu hatası" })
  }
})


router.get("/search", async (req, res) => {
  try {
    const query = req.query.q || ""
    const page = Number(req.query.page) || 1
    const limit = 10

    if (!query.trim()) {
      return res.json({ results: [], total: 0, totalPages: 0, page })
    }

    const data = await searchDeals(query, page, limit)
    res.json(mapPaginatedDealsToDealCardResponse(data))
  } catch (e) {
    console.error(e)
    res.status(500).json({ error: "Sunucu hatası" })
  }
})

router.get("/:id", async (req, res) => { //MAPPED
  try {
    const deal = await getDealById(req.params.id)
    if (!deal) return res.status(404).json({ error: "Deal bulunamadı" })
    console.log(mapDealToDealDetailResponse(deal))
      res.json(mapDealToDealDetailResponse(deal))
  } catch (e) {
    console.error(e)
    res.status(500).json({ error: "Sunucu hatası" })
  }
})

router.post(  "/",  authRequiredMiddleware,  upload.array("images", 5),  async (req, res) => {
    try {
      const userId = req.user.userId;
      const dealCreateData = mapCreateDealRequestToDealCreateData(req.body, userId);
      const deal = await createDeal(dealCreateData, req.files || []);
      res.json(deal);
    } catch (err) {
      console.error(err);
      res.status(500).json({ error: "Sunucu hatası" });
    }
  }
);



module.exports = router
