"use server";

import {
  searchUser as searchUserData,
  getUserById as getUserByIdData,
  updateUserById as updateUserByIdData,
  deleteUserById as deleteUserByIdData,
  createUser,
  getAllUserExcept as getAllUserExceptData,
  getAllUsers as getAllUserData,
  updateUserStatus,
} from "@/models/users";
import {
  revokeTokenById as revokeTokenByIdData,
  grantTokenById as grantTokenByIdData,
  searchToken as searchTokenData,
} from "@/models/users";
import { hashPassword, spliceObject } from "@/utils/library";

export const createEmptyUser = async () => {
  return await createUser({});
};

export const searchUser = async (keyword) => {
  return await searchUserData(keyword);
};

export const getAllUser = async () => {
  return await getAllUser();
};

export const getAllUserExcept = async (exceptIds = []) => {
  return await getAllUserExceptData(exceptIds);
};

export const getUserById = async (id) => {
  return await getUserByIdData(id, { password: 0 });
};

export const updateUserById = async (data) => {
  const { selected, spliced } = spliceObject(data, ["_id"]);

  if (spliced.password) spliced.password = hashPassword(spliced.password);

  return await updateUserByIdData(selected._id, spliced);
};

export const updateUserStatusById = async (_id, status) => {
  return await updateUserStatus(_id, status);
};

export const deleteUserById = async (id) => {
  return await deleteUserByIdData(id);
};

export const deleteMultipleUser = async (ids) => {
  return await Promise.all(ids.map(async (id) => await deleteUserById(id)));
};

export const revokeTokenById = async (id) => {
  return await revokeTokenByIdData(id);
};

export const grantTokenById = async (id) => {
  return await grantTokenByIdData(id);
};

export const searchToken = async (keyword) => {
  return await searchTokenData(keyword);
};
