const express = require("express")
const authRequiredMiddleware = require("../middleware/authRequired.middleware")
const authOptionalMiddleware = require("../middleware/authOptional.middleware")
const {
  getCommentsByDealId,
  createComment,
  deleteComment,
} = require("../services/comment.service")


const dealCommentAdapter=require("../adapters/responses/comment.adapter")
const commentService=require("../services/comment.service")
const router = express.Router()

router.get("/:dealId", async (req, res) => {
  try {
    const dealId = Number(req.params.dealId)
    const comments = await commentService.getCommentsByDealId(dealId)
    res.json(dealCommentAdapter.mapCommentsToDealCommentResponse(comments))

  } catch (err) {
    console.log(err.message)
    res.status(400).json({ error: err.message })
  }
})

router.post("/", authRequiredMiddleware
, async (req, res) => {
  try {
    const { dealId, text } = req.body
    const userId = req.user.userId
    if (!text?.trim()) return res.status(400).json({ error: "Yorum boş olamaz." })

    const comment = await createComment({ dealId, userId, text })
    res.json(comment)
  } catch (err) {
    console.error(err)
    res.status(500).json({ error: err.message || "Sunucu hatası" })
  }
})

router.delete("/:id", authRequiredMiddleware
, async (req, res) => {
  try {
    const result = await deleteComment(req.params.id, req.user.userId)
    res.json(result)
  } catch (err) {
    console.error(err)
    const status = err.message.includes("yetkin") ? 403 : 404
    res.status(status).json({ error: err.message })
  }
})

module.exports = router
