import { useUserApi } from "../../api/userApi.js";

const { postUser, putUser } = useUserApi();

export const addUser = async (userId = null) => {
    const name = document.getElementById('name');
    const username = document.getElementById('username');
    const email = document.getElementById('email');
    const password = document.getElementById('password');
    const role_id = document.getElementById('role_id');

    let userData = {
        'name' : name.value,
        'username' : username.value,
        'email': email.value,
        'role_id': role_id.value,
    }

    const emptyFields = Object.entries(userData).filter(([key, value]) => value === "");
    
    if (emptyFields.length > 0) {
        alert(`Por favor asegúrate de llenar todos los campos.`);
        return;
    }

    userData.password = password.value;

    if(userId) return await putUser({ id: userId, ...userData });
    else return await postUser(userData);
}