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

function assertPositiveInt(v, name = "id") {
  const n = Number(v)
  if (!Number.isInteger(n) || n <= 0) throw new Error(`Geçersiz ${name}.`)
  return n
}

async function updateAvatarUrl(userId, url) {
  const id = assertPositiveInt(userId, "userId")
  if (!url || typeof url !== "string" || !url.trim())
    throw new Error("Geçersiz URL.")

  const select = { id: true, username: true, avatarUrl: true }
  return userDb.updateUser({ id }, { avatarUrl: url.trim() }, { select })
}

async function getUserProfile(userId) {
  const id = assertPositiveInt(userId, "userId")
  const select = {
    id: true,
    username: true,
    email: true,
    avatarUrl: true,
    createdAt: true,
  }
  return userDb.findUser({ id }, { select })
}

module.exports = {
  updateAvatarUrl,
  getUserProfile,
}
