// routes/user.js
const express = require("express")
const router = express.Router()
const { validate } = require("../middleware/validate.middleware")
const optionalAuth = require("../middleware/optionalAuth")
const userService = require("../services/user.service")
const userProfileAdapter = require("../adapters/responses/userProfile.adapter")
const commentAdapter = require("../adapters/responses/comment.adapter")
const { mapPaginatedDealsToDealCardResponse } = require("../adapters/responses/dealCard.adapter")
const { endpoints } = require("@shared/contracts")
const {
  getUserProfileFromRedis,
  setUserProfileInRedis,
} = require("../services/redis/userProfileCache.service")

const { users } = endpoints
const PROFILE_PAGE_SIZE = 15
const PROFILE_CACHE_TTL_SECONDS = 60

function parsePage(value) {
  const num = Number(value)
  if (!Number.isInteger(num) || num < 1) return 1
  return num
}

router.get(
  "/:userName",
  validate(users.userProfileRequestSchema, "params", "validatedUserProfile"),
  async (req, res) => {
    try {
      const { userName } = req.validatedUserProfile
      const cached = await getUserProfileFromRedis(userName)
      if (cached) return res.json(cached)
      const data = await userService.getUserProfileByUsername(userName)

      const response = users.userProfileResponseSchema.parse(
        userProfileAdapter.mapUserProfileToResponse(data)
      )
      const payload = {
        ...response,
        dealsPagination: data.dealsPagination,
        commentsPagination: data.commentsPagination,
      }
      await setUserProfileInRedis(userName, payload, { ttlSeconds: PROFILE_CACHE_TTL_SECONDS })
      res.json(payload)
    } catch (err) {
      console.error(err)
      const status = err.statusCode || 500
      res.status(status).json({
        message: err.message || "Profil bilgileri alinamadi.",
      })
    }
  }
)

router.get(
  "/:userName/comments",
  validate(users.userProfileRequestSchema, "params", "validatedUserProfile"),
  async (req, res) => {
    try {
      const { userName } = req.validatedUserProfile
      const page = parsePage(req.query.page)
      const payload = await userService.getUserCommentsByUsername(userName, {
        page,
        limit: PROFILE_PAGE_SIZE,
      })
      const mapped = payload.results.map(commentAdapter.mapCommentToUserCommentResponse)
      res.json({
        page: payload.page,
        total: payload.total,
        totalPages: payload.totalPages,
        limit: payload.limit,
        results: mapped,
      })
    } catch (err) {
      console.error(err)
      const status = err.statusCode || 500
      res.status(status).json({
        message: err.message || "Kullanici yorumlari alinamadi.",
      })
    }
  }
)

router.get(
  "/:userName/deals",
  optionalAuth,
  validate(users.userProfileRequestSchema, "params", "validatedUserProfile"),
  async (req, res) => {
    try {
      const { userName } = req.validatedUserProfile
      const page = parsePage(req.query.page)
      const payload = await userService.getUserDealsByUsername(userName, {
        page,
        limit: PROFILE_PAGE_SIZE,
        viewer: req.auth ? { userId: req.auth.userId, role: req.auth.role } : null,
      })
      const response = mapPaginatedDealsToDealCardResponse(payload)
      res.json(response)
    } catch (err) {
      console.error(err)
      const status = err.statusCode || 500
      res.status(status).json({
        message: err.message || "Kullanici deal'lari alinamadi.",
      })
    }
  }
)

module.exports = router
