const express = require("express")
const requireAuth = require("../middleware/requireAuth.js")
const optionalAuth = require("../middleware/optionalAuth")
const { validate } = require("../middleware/validate.middleware")
const { endpoints } = require("@shared/contracts")
const { createComment, deleteComment } = require("../services/comment.service")

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

const { comments } = endpoints

router.get(
  "/:dealId",
  optionalAuth,
  validate(comments.commentListRequestSchema, "params", "validatedDealId"),
  async (req, res) => {
    try {
      const { dealId } = req.validatedDealId
      const { parentId, page, limit, sort } = req.query
      const payload = await commentService.getCommentsByDealId(dealId, {
        parentId,
        page,
        limit,
        sort,
        viewer: req.auth ? { userId: req.auth.userId } : null,
      })
      const mapped = dealCommentAdapter.mapCommentsToDealCommentResponse(payload.results)
      res.json(
        comments.commentListResponseSchema.parse({
          page: payload.page,
          total: payload.total,
          totalPages: payload.totalPages,
          results: mapped,
        })
      )
    } catch (err) {
      res.status(400).json({ error: err.message })
    }
  }
)

router.post(
  "/",
  requireAuth,
  validate(comments.commentCreateRequestSchema, "body", "validatedCommentPayload"),
  async (req, res) => {
    try {
      const { dealId, text, parentId } = req.validatedCommentPayload
      const userId = req.auth.userId

      const comment = await createComment({ dealId, userId, text, parentId })
      const mapped = dealCommentAdapter.mapCommentToDealCommentResponse(comment)
      res.json(comments.commentCreateResponseSchema.parse(mapped))
    } catch (err) {
      res.status(500).json({ error: err.message || "Sunucu hatasi" })
    }
  }
)

router.delete(
  "/:id",
  requireAuth,
  validate(comments.commentDeleteRequestSchema, "params", "validatedDeleteComment"),
  async (req, res) => {
    try {
      const { id } = req.validatedDeleteComment
      const result = await deleteComment(id, req.auth.userId)
      res.json(comments.commentDeleteResponseSchema.parse(result))
    } catch (err) {
      const status = err.message?.includes("yetkin") ? 403 : 404
      res.status(status).json({ error: err.message })
    }
  }
)

module.exports = router
