import bcrypt from "bcrypt";
import userModel from "./user.model";
import { IUser } from "./user.interface";

export class UserService {

    async getAll() {

        return await userModel
        .find()
        .populate("roleId");
    }

    async getById(
        id:string
    ) {
        return await userModel
        .findById(id)
        .populate("roleId");
    }

    async create(
        data:IUser
    ) {
        const passwordHash = await bcrypt.hash(
            data.passwordHash,
            10
        );

        data.passwordHash = passwordHash;
        
        return await userModel.create(data);
    }

    async update(
        id:string,
        data:Partial<IUser>
    ) {
        if(data.passwordHash){
            data.passwordHash = await bcrypt.hash(
                data.passwordHash,
                10
            );
        }
        return await userModel.findByIdAndUpdate(
            id,
            data,
            {
                new:true
            }
        );
    }

    async delete(
        id:string
    ) {
        return await userModel.findByIdAndDelete(
            id
        );
    }
}