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

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

enum Grade {
  G3
  G6
  G9
}

enum Subject {
  MATH
  READING
  WRITING
}

enum Difficulty {
  EASY
  MEDIUM
  HARD
}

enum SessionStatus {
  IN_PROGRESS
  COMPLETED
  ABANDONED
}

model User {
  id           String   @id @default(cuid())
  googleId     String?  @unique
  email        String   @unique
  displayName  String
  username     String   @unique
  avatarUrl    String?
  passwordHash String?
  createdAt    DateTime @default(now())
  updatedAt    DateTime @updatedAt

  sessions           GameSession[]
  leaderboardEntries LeaderboardEntry[]
  matchResults       MatchResult[]
}

model Question {
  id            String     @id @default(cuid())
  grade         Grade
  subject       Subject
  strand        String
  difficulty    Difficulty
  questionText  String
  options       Json
  correctAnswer String
  explanation   String?
  createdAt     DateTime   @default(now())

  answers UserAnswer[]
}

model GameSession {
  id             String        @id @default(cuid())
  userId         String
  grade          Grade
  subject        Subject
  status         SessionStatus @default(IN_PROGRESS)
  score          Int           @default(0)
  totalQuestions Int
  correctAnswers Int           @default(0)
  startedAt      DateTime      @default(now())
  completedAt    DateTime?

  user    User         @relation(fields: [userId], references: [id])
  answers UserAnswer[]
}

model UserAnswer {
  id             String   @id @default(cuid())
  sessionId      String
  questionId     String
  selectedAnswer String
  isCorrect      Boolean
  timeSpentMs    Int
  answeredAt     DateTime @default(now())

  session  GameSession @relation(fields: [sessionId], references: [id])
  question Question    @relation(fields: [questionId], references: [id])
}

model LeaderboardEntry {
  id           String   @id @default(cuid())
  userId       String
  grade        Grade
  elo          Int      @default(800)
  bestTime     Int?
  gamesPlayed  Int      @default(0)
  totalCorrect Int      @default(0)
  updatedAt    DateTime @updatedAt

  user User @relation(fields: [userId], references: [id])

  @@unique([userId, grade])
}

model MatchResult {
  id          String   @id @default(cuid())
  userId      String
  grade       Grade
  won         Boolean
  eloChange   Int
  eloAfter    Int
  timeSpentMs Int?
  playedAt    DateTime @default(now())

  user User @relation(fields: [userId], references: [id])
}
