import {DBTransaction} from '@db/interfaces';
import {useGroups} from '@modules/chats/store/zustand/useGroups';
import {
  deactivateUser,
  deleteUser,
  saveUsers,
} from '@modules/chats/db/services/userService';
import {ChatUserStatus, HuDataMember} from '@modules/chats/interfaces';

import {usersMapper} from '../UsersMapper';

class UsersUpdaterServiceClass {
  async deactivateUser(id: number) {
    await deactivateUser(id);
  }
  async deleteUser(id: number) {
    await deleteUser(id);
  }

  async saveUsers(
    users: HuDataMember[],
    options?: {updateStore?: boolean; tx?: DBTransaction},
  ) {
    try {
      // Save users in memory
      this.updateUsersMapper(users);

      await saveUsers(users, options?.tx);

      if (options?.updateStore) {
        useGroups.getState().saveUserUpdatesBatch(users);
      }
    } catch (error) {
      // eslint-disable-next-line no-console
      console.log('Error saving users', error);
    }
  }

  updateUsersMapper(users: HuDataMember[]) {
    usersMapper.save(
      users.map(user => ({
        id: user.id,
        first_name: user.first_name,
        last_name: user.last_name,
        profile_picture: user.picture_asset_url,
        status: user.status as ChatUserStatus,
        deleted_at: user.deleted_at || null,
      })),
    );
  }
}

export const UsersUpdaterService = new UsersUpdaterServiceClass();
