const express = require("express")
const requireAuth = require("../middleware/requireAuth")
const { validate } = require("../middleware/validate.middleware")
const { endpoints } = require("@shared/contracts")
const voteService = require("../services/vote.service")
const router = express.Router()

const { votes } = endpoints

router.post(
  "/",
  requireAuth,
  validate(votes.voteRequestSchema, "body", "validatedVotePayload"),
  async (req, res) => {
    try {
      const { dealId, voteType } = req.validatedVotePayload
      const result = await voteService.voteDeal({
        dealId,
        voteType,
        userId: req.auth.userId,
      })
      res.json(votes.voteResponseSchema.parse(result))
    } catch (err) {
      const status = err.statusCode || 500
      res.status(status).json({ message: err.message || "Sunucu hatasi" })
    }
  }
)

router.get(
  "/:dealId",
  validate(votes.voteListRequestSchema, "params", "validatedVoteList"),
  async (req, res) => {
    try {
      const { dealId } = req.validatedVoteList
      const data = await voteService.getVotes(dealId)
      res.json(votes.voteListResponseSchema.parse({ votes: data }))
    } catch (err) {
      console.error(err)
      res.status(500).json({ error: "Sunucu hatasi" })
    }
  }
)

module.exports = router
