import debounce from "lodash.debounce";
import { User } from "../domain/userEntity";
import { updateUser } from "../domain/userModel";
import { UserStore } from "../domain/userStore";

type UpdateUserStore = Pick<
  UserStore,
  "user" | "updateUser" | "setUser"
>;

const deboucedTask = debounce((task) => Promise.resolve(task()), 500);

const updatePersonalInfoUseCase = (
  store: UpdateUserStore,
  payload: Partial<User>
): Promise<void> | undefined => {
  const updateArtifacts = store.user
    ? updateUser(store.user, payload)
    : store.user;

  if (updateArtifacts) {
    store.setUser(updateArtifacts.user);

    return deboucedTask(() => store.updateUser(payload));
  }
};

export { updatePersonalInfoUseCase };

export type { UpdateUserStore };
