import { BadRequestException, Injectable, NotFoundException, } from '@nestjs/common'; import { encodeCursor, decodeCursor } from '../common/http/cursor.js'; import type { Page } from '../common/http/page.js'; import type { User } from '../users/user.js'; import type { CreateChatDto } from './dto/create-chat.dto.js'; import type { Chat } from './chat.js'; import { ChatsRepository } from './chats.repository.js'; @Injectable() export class ChatsService { constructor(private readonly chatsRepository: ChatsRepository) {} create(input: CreateChatDto, currentUser: User): Promise { if (!input.member_ids.includes(currentUser.id)) throw new BadRequestException('Current user must be a chat member'); if (new Set(input.member_ids).size !== input.member_ids.length) throw new BadRequestException('Duplicate chat member'); return this.chatsRepository.create(input.title, input.member_ids); } async getForUser(chatId: string, currentUser: User): Promise { const chat = await this.chatsRepository.findForUser( chatId, currentUser, ); if (!chat) throw new NotFoundException(); return chat; } async listForUser( currentUser: User, limit: number, cursorValue?: string, ): Promise> { const scope = `chats:${currentUser.id}`; const cursor = cursorValue ? decodeCursor(cursorValue, scope) : undefined; const page = await this.chatsRepository.findPageForUser( currentUser, limit, cursor, ); const last = page.items.at(-1); return { items: page.items, next_cursor: page.hasMore && last ? encodeCursor({ scope, created_at: last.created_at, id: last.id, }) : null, }; } }