import bcrypt from "bcrypt";
import jwt from "jsonwebtoken";
import userModel from "../user/user.model";

export class AuthService {

    async login (
        userName:string,
        password:string
    ){
        const user =
        await userModel.findOne({
            userName
        }).populate("roleId");

        //Validador de usuario existente
        if (!user) {
            throw new Error("Usuario no encontrado");
        }

        const validPassword =
        await bcrypt.compare(
            password,
            user.passwordHash
        );

        if (!validPassword){
            throw new Error("Contraseña incorrecta");
        }

        user.lastLogin = new Date();
        await user.save();

        const role = user.roleId as any;

        const token = jwt.sign(
            {

                id:user._id,
                roleId: user.roleId,

                roleName:role.roleName
            },

            process.env.JWT_SECRET as string,
            {
                expiresIn:"8h"
            }
        );

        return {
            token,
            user:{
                id: user._id,

                employeeId:user.employeeId,

                userName:user.userName,

                roleId: role._id,

                rolename: role.roleName,

                active: user.active
            }
        };
    }
}