generator client {
  provider      = "prisma-client-js"
  // Include both OpenSSL variants to support host build (OpenSSL 3.x)
  // and container runtime (Debian bullseye, OpenSSL 1.1.x)
  binaryTargets = ["native", "debian-openssl-1.1.x", "debian-openssl-3.0.x"]
}

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

enum UserRole {
  ADMIN
  MANAGER
  AGENT
  COLLABORATOR
}

enum TicketStatus {
  PENDING
  AWAITING_ATTENDANCE
  PAUSED
  RESOLVED
}

enum TicketPriority {
  LOW
  MEDIUM
  HIGH
  URGENT
}

enum TicketChannel {
  EMAIL
  WHATSAPP
  CHAT
  PHONE
  API
  MANUAL
}

enum CommentVisibility {
  PUBLIC
  INTERNAL
}

model Team {
  id          String       @id @default(cuid())
  tenantId    String
  name        String
  description String?
  members     TeamMember[]
  queues      Queue[]
  createdAt   DateTime     @default(now())
  updatedAt   DateTime     @updatedAt

  @@index([tenantId, name])
}

model TeamMember {
  teamId    String
  userId    String
  isLead    Boolean    @default(false)
  assignedAt DateTime  @default(now())

  team Team @relation(fields: [teamId], references: [id], onDelete: Cascade)
  user User @relation(fields: [userId], references: [id], onDelete: Cascade)

  @@id([teamId, userId])
}

model Company {
  id          String   @id @default(cuid())
  tenantId    String
  name        String
  slug        String
  provisioningCode String   @unique
  isAvulso    Boolean  @default(false)
  contractedHoursPerMonth Float?
  cnpj        String?
  domain      String?
  phone       String?
  description String?
  address     String?
  createdAt   DateTime @default(now())
  updatedAt   DateTime @updatedAt

  users   User[]
  tickets Ticket[]

  @@unique([tenantId, slug])
  @@index([tenantId, name])
}

model User {
  id             String            @id @default(cuid())
  tenantId       String
  name           String
  email          String            @unique
  role           UserRole
  timezone       String            @default("America/Sao_Paulo")
  avatarUrl      String?
  companyId      String?
  teams          TeamMember[]
  requestedTickets Ticket[]        @relation("TicketRequester")
  assignedTickets  Ticket[]        @relation("TicketAssignee")
  comments       TicketComment[]
  createdAt      DateTime          @default(now())
  updatedAt      DateTime          @updatedAt

  company Company? @relation(fields: [companyId], references: [id])

  @@index([tenantId, role])
  @@index([tenantId, companyId])
}

model Queue {
  id        String   @id @default(cuid())
  tenantId  String
  name      String
  slug      String
  teamId    String?
  tickets   Ticket[]
  createdAt DateTime @default(now())
  updatedAt DateTime @updatedAt

  team Team? @relation(fields: [teamId], references: [id])

  @@unique([tenantId, slug])
}

model Ticket {
  id             String         @id @default(cuid())
  tenantId       String
  reference      Int            @default(0)
  subject        String
  summary        String?
  status         TicketStatus   @default(PENDING)
  priority       TicketPriority @default(MEDIUM)
  channel        TicketChannel  @default(EMAIL)
  queueId        String?
  requesterId    String
  assigneeId     String?
  slaPolicyId    String?
  companyId      String?
  dueAt          DateTime?
  firstResponseAt DateTime?
  resolvedAt     DateTime?
  closedAt       DateTime?
  createdAt      DateTime       @default(now())
  updatedAt      DateTime       @updatedAt

  requester User  @relation("TicketRequester", fields: [requesterId], references: [id])
  assignee  User? @relation("TicketAssignee", fields: [assigneeId], references: [id])
  queue     Queue? @relation(fields: [queueId], references: [id])
  slaPolicy SlaPolicy? @relation(fields: [slaPolicyId], references: [id])
  company   Company? @relation(fields: [companyId], references: [id])
  events    TicketEvent[]
  comments  TicketComment[]

  @@index([tenantId, status])
  @@index([tenantId, queueId])
  @@index([tenantId, assigneeId])
  @@index([tenantId, companyId])
}

model TicketEvent {
  id        String   @id @default(cuid())
  ticketId  String
  type      String
  payload   Json
  createdAt DateTime @default(now())

  ticket Ticket @relation(fields: [ticketId], references: [id], onDelete: Cascade)

  @@index([ticketId, createdAt])
}

model TicketComment {
  id         String            @id @default(cuid())
  ticketId   String
  authorId   String
  visibility CommentVisibility @default(INTERNAL)
  body       String
  attachments Json?
  createdAt  DateTime          @default(now())
  updatedAt  DateTime          @updatedAt

  ticket Ticket @relation(fields: [ticketId], references: [id], onDelete: Cascade)
  author User   @relation(fields: [authorId], references: [id])

  @@index([ticketId, visibility])
}

model SlaPolicy {
  id        String   @id @default(cuid())
  tenantId  String
  name      String
  description String?
  timeToFirstResponse Int?
  timeToResolution    Int?
  calendar Json?
  createdAt DateTime @default(now())
  updatedAt DateTime @updatedAt

  tickets Ticket[]

  @@unique([tenantId, name])
}

model AuthUser {
  id             String        @id @default(cuid())
  name           String?
  email          String        @unique
  emailVerified  Boolean       @default(false)
  image          String?
  role           String        @default("agent")
  tenantId       String?
  avatarUrl      String?
  machinePersona String?
  createdAt      DateTime      @default(now())
  updatedAt      DateTime      @updatedAt
  sessions       AuthSession[]
  accounts       AuthAccount[]
}

model AuthSession {
  id         String   @id @default(cuid())
  userId     String
  token      String   @unique
  expiresAt  DateTime
  ipAddress  String?
  userAgent  String?
  createdAt  DateTime @default(now())
  updatedAt  DateTime @updatedAt

  user AuthUser @relation(fields: [userId], references: [id], onDelete: Cascade)

  @@index([userId])
  @@index([token])
}

model AuthAccount {
  id                    String   @id @default(cuid())
  userId                String
  accountId             String
  providerId            String
  accessToken           String?
  refreshToken          String?
  accessTokenExpiresAt  DateTime?
  refreshTokenExpiresAt DateTime?
  scope                 String?
  idToken               String?
  password              String?
  createdAt             DateTime @default(now())
  updatedAt             DateTime @updatedAt

  user AuthUser @relation(fields: [userId], references: [id], onDelete: Cascade)

  @@unique([providerId, accountId])
  @@index([userId])
}

model AuthInvite {
  id           String   @id @default(cuid())
  email        String
  name         String?
  role         String   @default("agent")
  tenantId     String
  token        String   @unique
  status       String   @default("pending")
  expiresAt    DateTime
  createdAt    DateTime @default(now())
  updatedAt    DateTime @updatedAt
  createdById  String?
  acceptedAt   DateTime?
  acceptedById String?
  revokedAt    DateTime?
  revokedById  String?
  revokedReason String?

  events       AuthInviteEvent[]

  @@index([tenantId, status])
  @@index([tenantId, email])
}

model AuthInviteEvent {
  id        String   @id @default(cuid())
  inviteId  String
  type      String
  payload   Json?
  actorId   String?
  createdAt DateTime @default(now())

  invite AuthInvite @relation(fields: [inviteId], references: [id], onDelete: Cascade)

  @@index([inviteId, createdAt])
}

model AuthVerification {
  id         String   @id @default(cuid())
  identifier String
  value      String
  expiresAt  DateTime
  createdAt  DateTime @default(now())
  updatedAt  DateTime @updatedAt

  @@index([identifier])
}
