const { validationResult } = require('express-validator');
const { createUser, validateCredentials, buildAuthResponse } = require('../services/userService');

const handleValidation = (req) => {
  const errors = validationResult(req);
  if (!errors.isEmpty()) {
    const error = new Error(errors.array().map((e) => e.msg).join(', '));
    error.status = 400;
    throw error;
  }
};

const register = async (req, res, next) => {
  try {
    handleValidation(req);
    const user = await createUser(req.body);
    res.status(201).json(buildAuthResponse(user));
  } catch (error) {
    next(error);
  }
};

const login = async (req, res, next) => {
  try {
    handleValidation(req);
    const user = await validateCredentials(req.body);
    res.json(buildAuthResponse(user));
  } catch (error) {
    next(error);
  }
};

const profile = async (req, res) => {
  res.json({ user: req.user });
};

module.exports = {
  register,
  login,
  profile
};
