const { login, register, refreshSession } = require("../services/authService");

function loginController(req, res) {
  const password = typeof (req.body && req.body.password) === "string" ? req.body.password : "";
  const result = login(req.body && req.body.username, password);
  if (!result) {
    return res.status(401).json({ error: "invalid credentials" });
  }
  return res.json(result);
}

function registerController(req, res) {
  const password = typeof (req.body && req.body.password) === "string" ? req.body.password : "";
  const result = register(req.body && req.body.username, password);
  if (result.error) {
    return res.status(result.status).json({ error: result.error });
  }
  return res.status(result.status).json(result.data);
}

function refreshController(req, res) {
  try {
    const refreshToken = req.body && req.body.refreshToken;
    const result = refreshSession(refreshToken);
    if (!result) {
      return res.status(401).json({ error: "invalid refresh token" });
    }
    return res.json(result);
  } catch {
    return res.status(401).json({ error: "invalid refresh token" });
  }
}

function validateTokenController(req, res) {
  return res.json({
    ok: true,
    user: {
      id: req.user.id,
      username: req.user.username,
      role: req.user.role
    }
  });
}

module.exports = {
  loginController,
  registerController,
  refreshController,
  validateTokenController
};
