const AuthService = require('../services/authService');
const { validateRegistration, validateLogin } = require('../validators/authValidator');
const { ApiError } = require('../utils/apiError');

class AuthController {
  static async register(req, res, next) {
    try {
      const { error } = validateRegistration(req.body);
      if (error) throw new ApiError(400, error.details[0].message);

      const user = await AuthService.register(req.body);
      res.status(201).json({ success: true, data: user });
    } catch (error) {
      next(error);
    }
  }

  static async login(req, res, next) {
    try {
      const { error } = validateLogin(req.body);
      if (error) throw new ApiError(400, error.details[0].message);

      const tokens = await AuthService.login(req.body);
      res.json({ success: true, data: tokens });
    } catch (error) {
      next(error);
    }
  }

  static async refreshToken(req, res, next) {
    try {
      const tokens = await AuthService.refreshToken(req.body.refreshToken);
      res.json({ success: true, data: tokens });
    } catch (error) {
      next(error);
    }
  }
}

module.exports = AuthController;
