Files
SerpentRace/SerpentRace_Backend/src/Application/Chat/commands/CreateChatCommandHandler.ts
T

86 lines
3.2 KiB
TypeScript

import { CreateChatCommand } from './ChatCommands';
import { IChatRepository } from '../../../Domain/IRepository/IChatRepository';
import { IUserRepository } from '../../../Domain/IRepository/IUserRepository';
import { ChatType, ChatAggregate } from '../../../Domain/Chat/ChatAggregate';
import { UserState } from '../../../Domain/User/UserAggregate';
import { logAuth, logError } from '../../Services/Logger';
export class CreateChatCommandHandler {
constructor(
private chatRepository: IChatRepository,
private userRepository: IUserRepository
) {}
async execute(command: CreateChatCommand): Promise<ChatAggregate | null> {
try {
// Validate creator exists
const creator = await this.userRepository.findById(command.createdBy);
if (!creator) {
throw new Error('Creator not found');
}
// For group chats, check if creator is premium
if (command.type === 'group' && creator.state !== UserState.VERIFIED_PREMIUM) {
throw new Error('Premium subscription required to create groups');
}
// Validate all target users exist
const targetUsers = await Promise.all(
command.userIds.map(id => this.userRepository.findById(id))
);
if (targetUsers.some(user => !user)) {
throw new Error('One or more target users not found');
}
// For direct chats, check if already exists
if (command.type === 'direct' && command.userIds.length === 1) {
const existingChats = await this.chatRepository.findByUserId(command.createdBy);
const existingDirectChat = existingChats.find(chat =>
chat.type === ChatType.DIRECT &&
chat.users.length === 2 &&
chat.users.includes(command.userIds[0])
);
if (existingDirectChat) {
return existingDirectChat;
}
}
// For game chats, check if already exists
if (command.type === 'game' && command.gameId) {
const existingGameChat = await this.chatRepository.findByGameId(command.gameId);
if (existingGameChat) {
return existingGameChat;
}
}
// Create chat
const chatData: Partial<ChatAggregate> = {
type: command.type as any,
name: command.name,
gameId: command.gameId,
createdBy: command.createdBy,
users: [command.createdBy, ...command.userIds],
messages: [],
lastActivity: new Date()
};
const chat = await this.chatRepository.create(chatData);
logAuth('Chat created successfully', command.createdBy, {
chatId: chat.id,
chatType: command.type,
participantCount: chat.users.length,
gameId: command.gameId
});
return chat;
} catch (error) {
logError('CreateChatCommandHandler error', error as Error);
return null;
}
}
}