generator client {
  provider = "prisma-client-js"
}

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

model User {
  id        String   @id @default(cuid())
  username  String   @unique
  email     String   @unique
  password  String
  avatar    String?
  isOnline  Boolean  @default(false)
  lastSeen  DateTime @default(now())
  createdAt DateTime @default(now())
  updatedAt DateTime @updatedAt

  messages     Message[]
  reactions    MessageReaction[]
  chatRooms    ChatRoomMember[]
  createdRooms ChatRoom[]
  seenMessages MessageSeen[]

  @@map("users")
}

model ChatRoom {
  id          String   @id @default(cuid())
  name        String
  description String?
  isPrivate   Boolean  @default(false)
  createdAt   DateTime @default(now())
  updatedAt   DateTime @updatedAt

  createdBy String
  creator   User   @relation(fields: [createdBy], references: [id])

  messages Message[]
  members  ChatRoomMember[]

  @@map("chat_rooms")
}

model ChatRoomMember {
  id       String   @id @default(cuid())
  userId   String
  roomId   String
  joinedAt DateTime @default(now())
  role     String   @default("member") // member, admin

  user User     @relation(fields: [userId], references: [id], onDelete: Cascade)
  room ChatRoom @relation(fields: [roomId], references: [id], onDelete: Cascade)

  @@unique([userId, roomId])
  @@map("chat_room_members")
}

model Message {
  id        String   @id @default(cuid())
  content   String
  image     String?
  createdAt DateTime @default(now())
  updatedAt DateTime @updatedAt

  userId String
  roomId String

  user User     @relation(fields: [userId], references: [id], onDelete: Cascade)
  room ChatRoom @relation(fields: [roomId], references: [id], onDelete: Cascade)

  reactions MessageReaction[]
  seenBy    MessageSeen[]

  @@map("messages")
}

model MessageSeen {
  id     String   @id @default(cuid())
  seenAt DateTime @default(now())

  userId    String
  messageId String

  user    User    @relation(fields: [userId], references: [id], onDelete: Cascade)
  message Message @relation(fields: [messageId], references: [id], onDelete: Cascade)

  @@unique([userId, messageId])
  @@map("message_seen")
}

model MessageReaction {
  id        String   @id @default(cuid())
  type      String // like, love, laugh, etc.
  createdAt DateTime @default(now())

  userId    String
  messageId String

  user    User    @relation(fields: [userId], references: [id], onDelete: Cascade)
  message Message @relation(fields: [messageId], references: [id], onDelete: Cascade)

  @@unique([userId, messageId, type])
  @@map("message_reactions")
}
