import {DBTransaction} from '@db/interfaces';
import {ChatUserStatus, HuDataMember} from '@modules/chats/interfaces';
import {mapHuMemberToDB} from '@modules/chats/utils';
import {INACTIVE_USER_STATUSES} from '@modules/chats/constants';
import {asyncMap} from '@shared/utils';

import {
  getUserById,
  updateUserStatus,
  insertUsers,
} from '../repositories/users';
import {InsertUser} from '../interfaces';
import {deleteUserAllMemberships} from '../repositories/groupMemberships';

export const deactivateUser = async (id: number) => {
  await updateUserStatus({id, status: ChatUserStatus.Deactivated});
};

export const deleteUser = async (id: number) => {
  await updateUserStatus({id, status: ChatUserStatus.Deleted});
};

export const isUserExists = async (id: number) => {
  const user = await getUserById(id);
  return !!user;
};

export const saveUsers = async (users: HuDataMember[], tx?: DBTransaction) => {
  const usersToSave = users.map(mapHuMemberToDB);

  // Split in chunks of 200
  const chunkSize = 200;
  const chunks: InsertUser[][] = [];

  for (let i = 0; i < usersToSave.length; i += chunkSize) {
    chunks.push(usersToSave.slice(i, i + chunkSize));
  }

  // Process all chunks in parallel
  await asyncMap(chunks, chunk => insertUsers(chunk, tx));

  const inactiveUsers = users.filter(
    user => user.status in INACTIVE_USER_STATUSES,
  );

  // Delete memberships for inactive users
  if (inactiveUsers.length) {
    await asyncMap(inactiveUsers, user =>
      deleteUserAllMemberships(user.id, tx),
    );
  }
};
