import bcrypt from 'bcrypt';
import jwt from 'jsonwebtoken';
import User from '../models/User.js';
import { sendActivationEmail } from './emailService.js';

const register = async (email, password) => {
  try {
    const activationCode = Math.random().toString(36).substring(2, 15);
    const user = await User.create({ email, password, activationCode });
    await sendActivationEmail(email, activationCode);
    return user;
  } catch (error) {
    console.log(error);
    return null;
  }
};

const activateUser = async (activationCode) => {
  const user = await User.findOne({ where: { activationCode } });
  if (!user) throw new Error('Invalid activation code');
  user.isActive = true;
  user.activationCode = null;
  await user.save();
  return user;
};

const login = async (email, password) => {
  const user = await User.findOne({ where: { email } });
  if (!user || !user.isActive) throw new Error('Invalid email or password.');
  const isPasswordValid = await bcrypt.compare(password, user.password);
  if (!isPasswordValid) throw new Error('Invalid email or password!');
  const token = jwt.sign({ userId: user.hashedId }, process.env.JWT_SECRET, { expiresIn: '1h' });
  user.authCode = token;
  await user.save();
  return { token };
};

const logout = async(userId, authToken) => {
  const user = await User.findOne({ where: { id: userId, authToken: authToken }});
  if (!user) {
    throw new Error('not found');
  }
  user.update({ authToken: null });
}

export { register, activateUser, login, logout };
