const express = require("express")
const multer = require("multer")
const requireAuth = require("../middleware/requireAuth.js")
const { getUserProfile } = require("../services/profile.service")
const { endpoints } = require("@shared/contracts")

const router = express.Router()
const upload = multer({ dest: "uploads/" })

const { updateUserAvatar } = require("../services/avatar.service")

const { account } = endpoints

router.post(
  "/avatar",
  requireAuth,
  upload.single("file"),
  async (req, res) => {
    try {
      const updatedUser = await updateUserAvatar(req.auth.userId, req.file)

      res.json(
        account.avatarUploadResponseSchema.parse({
          message: "Avatar updated",
          user: updatedUser,
        })
      )
    } catch (err) {
      console.error(err)
      res.status(400).json({ error: err.message })
    }
  }
)

router.get("/me", requireAuth, async (req, res) => {
  try {
    const user = await getUserProfile(req.auth.userId)
    res.json(account.accountMeResponseSchema.parse(user))
  } catch (err) {
    res.status(400).json({ error: err.message })
  }
})

module.exports = router
