generator client {
  provider = "prisma-client-js"
  output   = "../node_modules/@chat-service/prisma-client"
}

datasource db {
  provider = "postgresql"
  url      = env("CHAT_DATABASE_URL")
}

enum UserRole {
  admin
  user
}

enum SupportConversationStatus {
  open
  closed
}

model SupportConversation {
  id                 String                    @id @default(cuid())
  userId             String                    @unique
  userEmail          String
  assignedAdminId    String?
  assignedAdminEmail String?
  status             SupportConversationStatus @default(open)
  userLastReadAt     DateTime?
  adminLastReadAt    DateTime?
  lastMessageAt      DateTime                  @default(now())
  lastUserMessageAt  DateTime?
  lastAdminMessageAt DateTime?
  createdAt          DateTime                  @default(now())
  updatedAt          DateTime                  @updatedAt
  messages           SupportMessage[]

  @@index([status, lastMessageAt])
  @@index([assignedAdminId])
}

model SupportMessage {
  id              String              @id @default(cuid())
  conversationId  String
  authorId        String
  authorEmail     String
  authorRole      UserRole
  body            String
  createdAt       DateTime            @default(now())
  updatedAt       DateTime            @updatedAt
  conversation    SupportConversation @relation(fields: [conversationId], references: [id], onDelete: Cascade)

  @@index([conversationId, createdAt])
  @@index([authorId, createdAt])
}
