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

const requireAuth = require("../middleware/requireAuth")
const { endpoints } = require("@shared/contracts")
const { findSellerFromLink } = require("../services/seller.service")

const { seller } = endpoints

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" })
  }
})

module.exports = router
