const express = require("express")
const multer = require("multer")
const fs = require("fs")
const { uploadProfileImage } = require("../services/supabaseUpload.service")
const { validateImage } = require("../utils/validateImage")
const authRequiredMiddleware = require("../middleware/authRequired.middleware")
const authOptionalMiddleware = require("../middleware/authOptional.middleware")
const { getUserProfile } = require("../services/profile.service")

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

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

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

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


router.get("/me", authRequiredMiddleware
, async (req, res) => {
  try {
    const user = await getUserProfile(req.user.id)
    res.json(user)
  } catch (err) {
    res.status(400).json({ error: err.message })
  }
})

module.exports = router
