import bcrypt from 'bcrypt';
import validator from 'validator';
import userModel from '../models/userModel.js';
import { createToken } from '../utils/jwtHelper.js';

export async function signUp({ userName, email, password }) {
    if (await userModel.findOne({ email })) {
        throw new Error('User already exists');
    }

    if (!validator.isEmail(email)) {
        throw new Error('Invalid email address');
    }

    if (!validator.isStrongPassword(password, { minLength: 8 })) {
        throw new Error('Weak password. Use uppercase, lowercase, number, and symbol');
    }

    const hashedPassword = await bcrypt.hash(password, 10);
    const user = await userModel.create({ userName, email, password: hashedPassword });

    const token = createToken({ id: user._id });
    return { user, token };
}

export async function login({ email, password }) {
    const user = await userModel.findOne({ email });
    if (!user) throw new Error('No account found with this email');

    const isMatch = await bcrypt.compare(password, user.password);
    if (!isMatch) throw new Error('Invalid credentials');

    const token = createToken({ id: user._id });
    return { user, token };
}
