import { DataSource } from 'typeorm';
import { UserEntity } from '../../../entities';
import { SaveUserCommand } from '../../types';

export async function handleSaveUser(command: SaveUserCommand, dataSource: DataSource): Promise<void> {
  const repo = dataSource.getRepository(UserEntity);
  const { user } = command.payload;
  const entity = repo.create({
    id: user.id,
    oderId: user.oderId ?? null,
    username: user.username ?? null,
    displayName: user.displayName ?? null,
    description: user.description ?? null,
    profileUpdatedAt: user.profileUpdatedAt ?? null,
    avatarUrl: user.avatarUrl ?? null,
    avatarHash: user.avatarHash ?? null,
    avatarMime: user.avatarMime ?? null,
    avatarUpdatedAt: user.avatarUpdatedAt ?? null,
    status: user.status ?? null,
    role: user.role ?? null,
    joinedAt: user.joinedAt ?? null,
    peerId: user.peerId ?? null,
    isOnline: user.isOnline ? 1 : 0,
    isAdmin: user.isAdmin ? 1 : 0,
    isRoomOwner: user.isRoomOwner ? 1 : 0,
    voiceState: user.voiceState != null ? JSON.stringify(user.voiceState) : null,
    screenShareState: user.screenShareState != null ? JSON.stringify(user.screenShareState) : null
  });

  await repo.save(entity);
}
