const express = require("express")
const router = express.Router()

const requireAuth = require("../middleware/requireAuth")
const optionalAuth = require("../middleware/optionalAuth")
const { validate } = require("../middleware/validate.middleware")
const { endpoints } = require("@shared/contracts")
const { getSellerByName, getDealsBySellerName } = require("../services/seller.service")
const { findSellerFromLink } = require("../services/sellerLookup.service")
const { mapSellerToSellerDetailsResponse } = require("../adapters/responses/sellerDetails.adapter")
const { mapPaginatedDealsToDealCardResponse } = require("../adapters/responses/dealCard.adapter")

const { seller, deals } = endpoints

const buildViewer = (req) =>
  req.auth ? { userId: req.auth.userId, role: req.auth.role } : null

const listQueryValidator = validate(deals.dealsListRequestSchema, "query", "validatedDealListQuery")

router.post("/from-link", requireAuth, async (req, res) => {
  try {
    const sellerUrl = req.body.url
    const sellerLookup = await findSellerFromLink(sellerUrl)

    const response = seller.sellerLookupResponseSchema.parse(
      sellerLookup
        ? {
            found: true,
            seller: {
              id: sellerLookup.id,
              name: sellerLookup.name,
              url: sellerLookup.url ?? null,
            },
          }
        : { found: false, seller: null }
    )

    return res.json(response)
  } catch (e) {
    console.error(e)
    res.status(500).json({ error: "Sunucu hatasi" })
  }
})

router.get("/:sellerName", async (req, res) => {
  try {
    const sellerName = req.params.sellerName
    const sellerInfo = await getSellerByName(sellerName)
    if (!sellerInfo) return res.status(404).json({ error: "Seller bulunamadi" })

    res.json(mapSellerToSellerDetailsResponse(sellerInfo))
  } catch (e) {
    const status = e.statusCode || 500
    res.status(status).json({ error: e.message || "Sunucu hatasi" })
  }
})

router.get("/:sellerName/deals", optionalAuth, listQueryValidator, async (req, res) => {
  try {
    const sellerName = req.params.sellerName
    const { q, page, limit } = req.validatedDealListQuery

    const { payload } = await getDealsBySellerName(sellerName, {
      page,
      limit,
      filters: req.query,
      viewer: buildViewer(req),
    })

    const response = mapPaginatedDealsToDealCardResponse(payload)
    res.json(response.results)
  } catch (e) {
    const status = e.statusCode || 500
    res.status(status).json({ error: e.message || "Sunucu hatasi" })
  }
})

module.exports = router
