generator client {
  provider      = "prisma-client-js"
  binaryTargets = ["native", "linux-musl-openssl-3.0.x"]
}

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

model StudentTeacherAssignment {
  id        String   @id @default(uuid())
  studentId String   @map("student_id")
  teacherId String   @map("teacher_id")
  createdAt DateTime @default(now()) @map("created_at")
  student   User     @relation("StudentTeachers", fields: [studentId], references: [id], onDelete: Cascade)
  teacher   User     @relation("TeacherStudents", fields: [teacherId], references: [id], onDelete: Cascade)

  @@unique([studentId, teacherId])
  @@map("student_teacher_assignments")
}

model User {
  id                  String                   @id @default(uuid())
  name                String
  email               String                   @unique
  password            String
  role                UserRole                 @default(STUDENT)
  canCreateBots       Boolean                  @default(false) @map("can_create_bots")
  canEditBots         Boolean                  @default(false) @map("can_edit_bots")
  refreshToken        String?                  @map("refresh_token")
  emailVerified       Boolean                  @default(false) @map("email_verified")
  profileImageUrl     String?                  @map("profile_image_url")
  assignedTeachers    StudentTeacherAssignment[] @relation("StudentTeachers")
  assignedStudents    StudentTeacherAssignment[] @relation("TeacherStudents")
  createdAt           DateTime                 @default(now()) @map("created_at")
  updatedAt         DateTime           @updatedAt @map("updated_at")
  conversations     Conversation[]     @relation("StudentConversations")
  feedbackGiven     Feedback[]         @relation("TeacherFeedback")
  grantedAccesses   StudentBotAccess[] @relation("GrantedBy")
  botAccesses       StudentBotAccess[] @relation("StudentAccesses")
  notifications     Notification[]     @relation("UserNotifications")
  createdBots       Bot[]              @relation("BotCreator")
  quotaGrants       QuotaGrant[]       @relation("UserQuotaGrants")
  usageLedger       UsageLedger[]      @relation("UserUsageLedger")

  @@map("users")
}

model Bot {
  id              String             @id @default(uuid())
  name            String
  topic           String
  level           Level
  imageUrl        String?            @map("image_url")
  agentId         String             @map("agent_id")
  description     String
  feedback        String?
  isActive        Boolean            @default(true) @map("is_active")
  createdAt       DateTime           @default(now()) @map("created_at")
  updatedAt       DateTime           @updatedAt @map("updated_at")
  isTimerEnabled  Boolean            @default(false) @map("is_timer_enabled")
  maxUsageSeconds Int?               @map("max_usage_seconds")
  createdBy       String?            @map("created_by")
  conversations   Conversation[]     @relation("BotConversations")
  accesses        StudentBotAccess[]
  creator         User?              @relation("BotCreator", fields: [createdBy], references: [id])

  @@map("bots")
}

model Conversation {
  id                       String                @id @default(uuid())
  studentId                String                @map("student_id")
  botId                    String                @map("bot_id")
  transcript               String?
  startedAt                DateTime              @map("started_at")
  endedAt                  DateTime?             @map("ended_at")
  durationSeconds          Int?                  @map("duration_seconds")
  audioUrl                 String?               @map("audio_url")
  summary                  String?
  aiAnalysis               String?               @map("ai_analysis")
  elevenLabsConversationId String?               @map("elevenlabs_conversation_id")
  audioTranscript          String?               @map("audio_transcript")
  voiceAnalysis            String?               @map("voice_analysis")
  conversationMode         ConversationMode      @default(TEXT) @map("conversation_mode")
  openaiSummary            String?               @map("openai_summary")
  openaiEvaluation         String?               @map("openai_evaluation")
  openaiFeedback           String?               @map("openai_feedback")
  openaiTranscript         String?               @map("openai_transcript")
  feedbackStatus           String?               @default("pending_transcript") @map("feedback_status")
  createdAt                DateTime              @default(now()) @map("created_at")
  updatedAt                DateTime              @updatedAt @map("updated_at")
  bot                      Bot                   @relation("BotConversations", fields: [botId], references: [id], onDelete: Cascade)
  student                  User                  @relation("StudentConversations", fields: [studentId], references: [id], onDelete: Cascade)
  feedback                 Feedback[]            @relation("ConversationFeedback")
  messages                 Message[]             @relation("ConversationMessages")
  sessions                 ConversationSession[] @relation("ConversationSessions")

  @@map("conversations")
}

model ConversationSession {
  id              String       @id @default(uuid())
  conversationId  String       @map("conversation_id")
  startedAt       DateTime     @default(now()) @map("started_at")
  endedAt         DateTime?    @map("ended_at")
  durationSeconds Int?         @map("duration_seconds")
  createdAt       DateTime     @default(now()) @map("created_at")
  updatedAt       DateTime     @updatedAt @map("updated_at")
  conversation    Conversation @relation("ConversationSessions", fields: [conversationId], references: [id], onDelete: Cascade)

  @@map("conversation_sessions")
}

model Message {
  id             String        @id @default(uuid())
  conversationId String        @map("conversation_id")
  senderType     MessageSender @map("sender_type")
  content        String
  messageType    MessageType   @default(TEXT) @map("message_type")
  audioUrl       String?       @map("audio_url")
  audioDuration  Float?        @map("audio_duration")
  timestamp      DateTime      @default(now())
  createdAt      DateTime      @default(now()) @map("created_at")
  updatedAt      DateTime      @updatedAt @map("updated_at")
  conversation   Conversation  @relation("ConversationMessages", fields: [conversationId], references: [id], onDelete: Cascade)

  @@map("messages")
}

model Feedback {
  id             String       @id @default(uuid())
  conversationId String       @map("conversation_id")
  teacherId      String       @map("teacher_id")
  text           String
  rating         Int?
  createdAt      DateTime     @default(now()) @map("created_at")
  updatedAt      DateTime     @updatedAt @map("updated_at")
  conversation   Conversation @relation("ConversationFeedback", fields: [conversationId], references: [id], onDelete: Cascade)
  teacher        User         @relation("TeacherFeedback", fields: [teacherId], references: [id], onDelete: Cascade)

  @@map("feedback")
}

model StudentBotAccess {
  id                String    @id @default(uuid())
  studentId         String    @map("student_id")
  botId             String    @map("bot_id")
  grantedBy         String    @map("granted_by")
  grantedAt         DateTime  @default(now()) @map("granted_at")
  isLocked          Boolean   @default(false) @map("is_locked")
  lastUsageAt       DateTime? @map("last_usage_at")
  totalUsageSeconds Int       @default(0) @map("total_usage_seconds")
  notes             String?   @map("notes")
  bot               Bot       @relation(fields: [botId], references: [id])
  granter           User      @relation("GrantedBy", fields: [grantedBy], references: [id])
  student           User      @relation("StudentAccesses", fields: [studentId], references: [id])

  @@unique([studentId, botId])
  @@map("student_bot_access")
}

model RefreshToken {
  id        String   @id @default(uuid())
  token     String   @unique
  userId    String   @map("user_id")
  expiresAt DateTime @map("expires_at")
  createdAt DateTime @default(now()) @map("created_at")

  @@map("refresh_tokens")
}

model AuditLog {
  id        String   @id @default(uuid())
  userId    String?  @map("user_id")
  action    String
  resource  String
  details   Json?
  ipAddress String?  @map("ip_address")
  userAgent String?  @map("user_agent")
  createdAt DateTime @default(now()) @map("created_at")
  updatedAt DateTime @updatedAt @map("updated_at")

  @@map("audit_logs")
}

model ElevenLabsConfig {
  id        String   @id @default(uuid())
  apiKey    String   @map("api_key")
  isActive  Boolean  @default(true) @map("is_active")
  createdAt DateTime @default(now()) @map("created_at")
  updatedAt DateTime @updatedAt @map("updated_at")

  @@map("elevenlabs_config")
}

model OpenAIConfig {
  id          String   @id @default(uuid())
  apiKey      String   @map("api_key")
  assistantId String   @map("assistant_id")
  isActive    Boolean  @default(true) @map("is_active")
  createdAt   DateTime @default(now()) @map("created_at")
  updatedAt   DateTime @updatedAt @map("updated_at")

  @@map("openai_config")
}

model SystemConfig {
  id                     String   @id @default(uuid())
  quotaManagementEnabled Boolean  @default(true) @map("quota_management_enabled")
  isActive               Boolean  @default(true) @map("is_active")
  createdAt              DateTime @default(now()) @map("created_at")
  updatedAt              DateTime @updatedAt @map("updated_at")

  @@map("system_config")
}

model Notification {
  id        String           @id @default(uuid())
  userId    String           @map("user_id")
  title     String
  message   String
  type      NotificationType @default(BOT_ASSIGNED)
  data      Json?
  isRead    Boolean          @default(false) @map("is_read")
  readAt    DateTime?        @map("read_at")
  createdAt DateTime         @default(now()) @map("created_at")
  updatedAt DateTime         @updatedAt @map("updated_at")
  user      User             @relation("UserNotifications", fields: [userId], references: [id], onDelete: Cascade)

  @@map("notifications")
}

model QuotaGrant {
  id          String         @id @default(uuid())
  userId      String         @map("user_id")
  periodStart DateTime       @map("period_start")
  periodEnd   DateTime       @map("period_end")
  seconds     Int            @map("seconds")
  type        QuotaGrantType @default(BONUS)
  reason      String?
  expiresAt   DateTime?      @map("expires_at")
  createdAt   DateTime       @default(now()) @map("created_at")
  user        User           @relation("UserQuotaGrants", fields: [userId], references: [id], onDelete: Cascade)

  @@unique([userId, periodStart, type])
  @@index([userId, periodStart, periodEnd])
  @@map("quota_grant")
}

model UsageLedger {
  id                    String   @id @default(uuid())
  userId                String   @map("user_id")
  seconds               Int
  reason                String?
  source                String?
  relatedConversationId String?  @unique @map("related_conversation_id")
  createdAt             DateTime @default(now()) @map("created_at")
  user                  User     @relation("UserUsageLedger", fields: [userId], references: [id], onDelete: Cascade)

  @@index([userId, createdAt])
  @@map("usage_ledger")
}

enum UserRole {
  ADMIN
  TEACHER
  STUDENT
}

enum Level {
  A1
  A2
  B1
  B2
  C1
  C2
}

enum ConversationMode {
  TEXT
  VOICE
  MIXED
}

enum MessageSender {
  USER
  BOT
}

enum MessageType {
  TEXT
  VOICE
  AUDIO
}

enum NotificationType {
  BOT_ASSIGNED
}

enum QuotaGrantType {
  BASE
  BONUS
}
