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

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

enum UserRole {
  SUPER_ADMIN
  ADMIN
  HOD
  REPORTING_MANAGER
  EMPLOYEE
}

enum UserStatus {
  ACTIVE
  INACTIVE
}

enum TripStatus {
  CREATED
  STARTED
  TRAVELLING
  ARRIVED
  MEETING_STARTED
  MEETING_COMPLETED
  RETURN_TRIP
  COMPLETED
  CANCELLED
}

enum PunchType {
  DEPARTURE
  ARRIVAL
  MEETING_START
  MEETING_END
}

enum VehicleType {
  CAR
  BIKE
  SCOOTER
  OTHER
}

enum FuelType {
  PETROL
  DIESEL
  CNG
  ELECTRIC
  OTHER
}

enum LeadType {
  HOT
  WARM
  COLD
  EXISTING
  OTHER
}

enum NotificationType {
  TRIP_STARTED
  ARRIVAL_COMPLETED
  MEETING_STARTED
  MEETING_ENDED
  EMPLOYEE_OFFLINE
  GPS_STOPPED
}

enum EmployeePresence {
  ONLINE
  OFFLINE
  ON_TRIP
  IN_MEETING
  IDLE
}

model User {
  id                 String           @id @default(cuid())
  uid                String           @unique
  email              String           @unique
  passwordHash       String
  fullName           String
  employeeCode       String           @unique
  mobileNumber       String?
  sittingLocation    String?
  reportingManagerId String?
  reportingManager   User?            @relation("ReportingHierarchy", fields: [reportingManagerId], references: [id])
  directReports      User[]           @relation("ReportingHierarchy")
  role               UserRole         @default(EMPLOYEE)
  deviceId           String?
  profileImage       String?
  status             UserStatus       @default(ACTIVE)
  fcmToken           String?
  isRooted           Boolean          @default(false)
  presence           EmployeePresence @default(OFFLINE)
  lastSeenAt         DateTime?
  createdAt          DateTime         @default(now())
  updatedAt          DateTime         @updatedAt

  refreshTokens RefreshToken[]
  trips         Trip[]
  gpsPoints     GpsPoint[]
  auditLogs     AuditLog[]     @relation("AuditActor")
  notifications Notification[]

  @@index([role])
  @@index([status])
  @@index([reportingManagerId])
  @@index([presence])
}

model RefreshToken {
  id        String   @id @default(cuid())
  userId    String
  user      User     @relation(fields: [userId], references: [id], onDelete: Cascade)
  tokenHash String
  deviceId  String?
  expiresAt DateTime
  createdAt DateTime @default(now())

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

model PasswordResetToken {
  id        String   @id @default(cuid())
  email     String
  tokenHash String
  expiresAt DateTime
  consumed  Boolean  @default(false)
  createdAt DateTime @default(now())

  @@index([email])
  @@index([expiresAt])
}

model AuditLog {
  id          String   @id @default(cuid())
  actorUserId String?
  actor       User?    @relation("AuditActor", fields: [actorUserId], references: [id])
  actorEmail  String?
  action      String
  targetType  String?
  targetId    String?
  metadata    Json?
  ipAddress   String?
  userAgent   String?
  createdAt   DateTime @default(now())

  @@index([actorUserId, createdAt])
  @@index([createdAt])
  @@index([action])
}

model Trip {
  id                String       @id @default(cuid())
  tripId            String       @unique @default(uuid())
  userId            String
  user              User         @relation(fields: [userId], references: [id])
  city              String?
  fromLocation      String?
  toLocation        String?
  destinationLat    Float?
  destinationLng    Float?
  googlePlaceId     String?
  plannedDistance   Float?
  vehicleType       VehicleType?
  fuelType          FuelType?
  purpose           String?
  notes             String?
  status            TripStatus   @default(CREATED)
  totalDistance     Float        @default(0)
  travelDuration    Int          @default(0)
  idleTime          Int          @default(0)
  meetingDuration   Int          @default(0)
  productivityScore Float?
  tripEfficiency    Float?
  startedAt         DateTime?
  arrivedAt         DateTime?
  completedAt       DateTime?
  createdAt         DateTime     @default(now())
  updatedAt         DateTime     @updatedAt

  punches   Punch[]
  gpsPoints GpsPoint[]
  stops     GpsStop[]

  @@index([userId, status])
  @@index([status])
  @@index([createdAt])
  @@index([userId, createdAt])
}

model Punch {
  id             String    @id @default(cuid())
  tripId         String
  trip           Trip      @relation(fields: [tripId], references: [id], onDelete: Cascade)
  type           PunchType
  timestamp      DateTime
  latitude       Float
  longitude      Float
  address        String?
  batteryPercent Float?
  gpsAccuracy    Float?
  speed          Float?
  isMockLocation Boolean   @default(false)
  meetingSummary String?
  leadType       LeadType?
  customerNotes  String?
  createdAt      DateTime  @default(now())

  @@index([tripId, type])
  @@index([tripId, timestamp])
}

model GpsPoint {
  id            String   @id @default(cuid())
  tripId        String?
  trip          Trip?    @relation(fields: [tripId], references: [id], onDelete: SetNull)
  userId        String
  user          User     @relation(fields: [userId], references: [id])
  clientPointId String?
  latitude      Float
  longitude     Float
  accuracy      Float?
  speed         Float?
  bearing       Float?
  batteryLevel  Float?
  timestamp     DateTime
  isSmoothed    Boolean  @default(false)
  createdAt     DateTime @default(now())

  @@unique([tripId, clientPointId])
  @@index([tripId, timestamp])
  @@index([userId, timestamp])
}

model GpsStop {
  id        String    @id @default(cuid())
  tripId    String
  trip      Trip      @relation(fields: [tripId], references: [id], onDelete: Cascade)
  latitude  Float
  longitude Float
  startedAt DateTime
  endedAt   DateTime?
  duration  Int?
  address   String?

  @@index([tripId])
}

model Notification {
  id     String           @id @default(cuid())
  userId String
  user   User             @relation(fields: [userId], references: [id])
  type   NotificationType
  title  String
  body   String
  data   Json?
  read   Boolean          @default(false)
  sentAt DateTime         @default(now())

  @@index([userId, read])
  @@index([sentAt])
}

model SystemConfig {
  id        String   @id @default(cuid())
  key       String   @unique
  value     Json
  updatedAt DateTime @updatedAt

  @@map("system_config")
}

model DailySummary {
  id                String   @id @default(cuid())
  userId            String
  date              DateTime
  totalDistance     Float    @default(0)
  travelTime        Int      @default(0)
  meetingTime       Int      @default(0)
  idleTime          Int      @default(0)
  tripsCompleted    Int      @default(0)
  productivityScore Float?
  createdAt         DateTime @default(now())
  updatedAt         DateTime @updatedAt

  @@unique([userId, date])
  @@index([date])
}

model MonthlySummary {
  id                String @id @default(cuid())
  userId            String
  year              Int
  month             Int
  totalDistance     Float  @default(0)
  travelTime        Int    @default(0)
  meetingTime       Int    @default(0)
  idleTime          Int    @default(0)
  tripsCompleted    Int    @default(0)
  productivityScore Float?

  @@unique([userId, year, month])
  @@index([year, month])
}
