import { register, activateUser, login, logout, deleteOwnAccount, requestPasswordReset, resetPassword } from '../services/authService.js';

const registerUser = async (req, res, next) => {
  try {
    const { email, password } = req.body;
    console.log('registerUser', email, password);
    await register(email, password);
    console.log('registerUser done');
    // Aus Sicherheitsgründen KEINE Userdaten (Passwort-Hash, Aktivierungscode, ...) zurückgeben
    res.status(201).json({ success: true });
    console.log('registerUser response sent');
  } catch (error) {
    next(error);
  }
};

const activate = async (req, res, next) => {
  try {
    const { activationCode } = req.params;
    await activateUser(activationCode);
    // Auch bei Aktivierung kein komplettes User-Objekt zurückgeben
    res.status(200).json({ success: true });
  } catch (error) {
    next(error);
  }
};

const loginUser = async (req, res, next) => {
  try {
    const { email, password, rememberMe } = req.body;
    const result = await login(email, password, { rememberMe });
    res.status(200).json(result);
  } catch (error) {
    next(error);
  }
};

const logoutUser = async (req, res, next) => {
  try {
    const token = req.headers['authorization']?.split(' ')[1] || req.headers.authcode;
    const result = await logout(token);
    res.status(200).json(result);
  } catch (error) {
    next(error);
  }
};

const deleteAccount = async (req, res, next) => {
  try {
    const { password } = req.body || {};
    const result = await deleteOwnAccount(req.user?.id, password);
    res.status(200).json(result);
  } catch (error) {
    next(error);
  }
};

const forgotPassword = async (req, res, next) => {
  try {
    const { email } = req.body;
    const result = await requestPasswordReset(email);
    res.status(200).json(result);
  } catch (error) {
    next(error);
  }
};

const resetUserPassword = async (req, res, next) => {
  try {
    const { token, password } = req.body;
    const result = await resetPassword(token, password);
    res.status(200).json(result);
  } catch (error) {
    next(error);
  }
};

export { registerUser, activate, loginUser, logoutUser, deleteAccount, forgotPassword, resetUserPassword };
