const bcrypt = require("bcryptjs");
const generateToken  = require("../utils/generateToken");
const authDb = require("../db/auth.db");

async function login({ email, password }) {
  const user = await authDb.findUserByEmail(email);

  if (!user) {
    const err = new Error("Kullanıcı bulunamadı.");
    err.statusCode = 400;
    throw err;
  }

  const isMatch = await bcrypt.compare(password, user.passwordHash);
  if (!isMatch) {
    const err = new Error("Şifre hatalı.");
    err.statusCode = 401;
    throw err;
  }

  const token = generateToken(user.id);

  return {
    token,
    user: {
      id: user.id,
      username: user.username,
      email: user.email,
      avatarUrl: user.avatarUrl,
    },
  };
}

async function register({ username, email, password }) {
  const existingUser = await authDb.findUserByEmail(email);
  if (existingUser) {
    const err = new Error("Bu e-posta zaten kayıtlı.");
    err.statusCode = 400;
    throw err;
  }

  const passwordHash = await bcrypt.hash(password, 10);

  const user = await authDb.createUser({
    username,
    email,
    passwordHash,
  });

  const token = generateToken(user.id);

  return {
    token,
    user: {
      id: user.id,
      username: user.username,
      email: user.email,
      avatarUrl: user.avatarUrl ?? null,
    },
  };
}

async function getMe(userId) {
  const user = await authDb.findUserById(userId, {
    select: {
      id: true,
      username: true,
      email: true,
      avatarUrl: true,
    },
  });

  if (!user) {
    const err = new Error("Kullanıcı bulunamadı");
    err.statusCode = 404;
    throw err;
  }

  return user;
}
module.exports = { 
  login,
  register,
  getMe,
};
