const fs = require("fs")
const { uploadImage } = require("./uploadImage.service")
const { validateImage } = require("../utils/validateImage")

const userDB = require("../db/user.db")

async function updateUserAvatar(userId, file) {
  if (!file) {
    throw new Error("No file uploaded")
  }

  validateImage({
    mimetype: file.mimetype,
    size: file.size,
  })

  const buffer = fs.readFileSync(file.path)

  const imageUrl = await uploadImage({
    bucket: "avatars",
    path: `${userId}_${Date.now()}.jpg`,
    fileBuffer: buffer,
    contentType: file.mimetype,
  })

  fs.unlinkSync(file.path)

  return updateAvatarUrl(userId, imageUrl)
}


async function updateAvatarUrl(userId, imageUrl) {
  return userDB.updateUser(
    { id: userId },
    { avatarUrl: imageUrl },
    {
      select: {
        id: true,
        username: true,
        avatarUrl: true,
      },
    }
  )
}
module.exports = { updateUserAvatar }
