import { eq, asc, desc, type Db, conversations, messages } from '@mosaic/db'; /** Maximum number of conversations returned per list query. */ const MAX_CONVERSATIONS = 200; /** Maximum number of messages returned per conversation history query. */ const MAX_MESSAGES = 500; export type Conversation = typeof conversations.$inferSelect; export type NewConversation = typeof conversations.$inferInsert; export type Message = typeof messages.$inferSelect; export type NewMessage = typeof messages.$inferInsert; export function createConversationsRepo(db: Db) { return { async findAll(userId: string): Promise { return db .select() .from(conversations) .where(eq(conversations.userId, userId)) .orderBy(desc(conversations.updatedAt)) .limit(MAX_CONVERSATIONS); }, async findById(id: string): Promise { const rows = await db.select().from(conversations).where(eq(conversations.id, id)); return rows[0]; }, async create(data: NewConversation): Promise { const rows = await db.insert(conversations).values(data).returning(); return rows[0]!; }, async update(id: string, data: Partial): Promise { const rows = await db .update(conversations) .set({ ...data, updatedAt: new Date() }) .where(eq(conversations.id, id)) .returning(); return rows[0]; }, async remove(id: string): Promise { const rows = await db.delete(conversations).where(eq(conversations.id, id)).returning(); return rows.length > 0; }, async findMessages(conversationId: string): Promise { return db .select() .from(messages) .where(eq(messages.conversationId, conversationId)) .orderBy(asc(messages.createdAt)) .limit(MAX_MESSAGES); }, async addMessage(data: NewMessage): Promise { const rows = await db.insert(messages).values(data).returning(); return rows[0]!; }, }; } export type ConversationsRepo = ReturnType;