import { relations, sql } from 'drizzle-orm'; import { index, pgTable, text, timestamp, uuid } from 'drizzle-orm/pg-core'; import { users } from './auth'; import { matches } from './matching'; export const messages = pgTable( 'messages', { id: uuid('id').primaryKey().defaultRandom(), matchId: uuid('match_id') .notNull() .references(() => matches.id, { onDelete: 'cascade' }), senderId: uuid('sender_id') .notNull() .references(() => users.id, { onDelete: 'cascade' }), body: text('body').notNull(), attachments: text('attachments').array().notNull().default(sql`'{}'::text[]`), readAt: timestamp('read_at', { withTimezone: true }), createdAt: timestamp('created_at', { withTimezone: true }).notNull().defaultNow(), }, (t) => [ // Chat history is always "this match, newest last". index('messages_match_idx').on(t.matchId, t.createdAt), // Unread badge count. index('messages_unread_idx').on(t.matchId, t.senderId).where(sql`${t.readAt} IS NULL`), ], ); export const messagesRelations = relations(messages, ({ one }) => ({ match: one(matches, { fields: [messages.matchId], references: [matches.id] }), sender: one(users, { fields: [messages.senderId], references: [users.id] }), }));