generator client {
  provider = "prisma-client"
  output   = "../generated/client"
}

datasource db {
  provider = "mysql"
}

enum UserStatus {
  PENDING
  ACTIVE
  SUSPENDED
  BLOCKED
  CLOSED
}

enum RoleCode {
  SUPER_ADMIN
  ADMIN
  OPERATIONS_MANAGER
  DISPATCHER
  KYC_REVIEWER
  SUPPORT_AGENT
  FINANCE
  DRIVER
  CUSTOMER
}

enum Gender {
  MALE
  FEMALE
  OTHER
  PREFER_NOT_TO_SAY
}

enum DriverStatus {
  REGISTERED
  KYC_PENDING
  KYC_UNDER_REVIEW
  APPROVED
  REJECTED
  SUSPENDED
  BLOCKED
  INACTIVE
}

enum KycStatus {
  NOT_SUBMITTED
  SUBMITTED
  UNDER_REVIEW
  APPROVED
  REJECTED
  EXPIRED
}

enum VehicleStatus {
  PENDING
  APPROVED
  REJECTED
  SUSPENDED
  INACTIVE
}

enum VehicleType {
  BIKE
  AUTO
  MINI
  SEDAN
  SUV
  XL
  PREMIUM
}

enum DocumentType {
  PROFILE_PHOTO
  AADHAAR_FRONT
  AADHAAR_BACK
  PAN_CARD
  DRIVING_LICENSE
  RC_FRONT
  RC_BACK
  INSURANCE
  POLLUTION_CERTIFICATE
  FITNESS_CERTIFICATE
  PERMIT
  BANK_PROOF
  OTHER
}

enum DocumentStatus {
  PENDING
  VERIFIED
  REJECTED
  EXPIRED
}

model User {
  id               BigInt     @id @default(autoincrement())
  publicId         String     @unique @db.VarChar(36)
  mobile           String?    @unique @db.VarChar(20)
  email            String?    @unique @db.VarChar(191)
  passwordHash     String?    @db.VarChar(255)
  mobileVerifiedAt DateTime?  @db.DateTime(3)
  emailVerifiedAt  DateTime?  @db.DateTime(3)
  status           UserStatus @default(PENDING)
  lastLoginAt      DateTime?  @db.DateTime(3)
  createdAt        DateTime   @default(now()) @db.DateTime(3)
  updatedAt        DateTime   @updatedAt @db.DateTime(3)

  roles             UserRole[]
  customer          Customer?
  driver            Driver?
  bookings          Booking[]          @relation("CustomerUserBookings")
  wallet            Wallet?
  payments          Payment[]
  couponRedemptions CouponRedemption[]
  ratingsGiven      Rating[]           @relation("RatingGivenBy")
  ratingsReceived   Rating[]           @relation("RatingReceivedBy")
  supportTickets    SupportTicket[]    @relation("SupportTicketRequester")
  supportMessages   SupportMessage[]   @relation("SupportMessageAuthor")
  notifications     Notification[]
  emergencyEvents   EmergencyEvent[]   @relation("EmergencyRaisedBy")
  otpChallenges     OtpChallenge[]
  authSessions      AuthSession[]
  loginAttempts     LoginAttempt[]

  @@index([status])
  @@index([createdAt])
  @@map("users")
}

model Role {
  id          Int      @id @default(autoincrement())
  code        RoleCode @unique
  name        String   @db.VarChar(100)
  description String?  @db.VarChar(255)
  createdAt   DateTime @default(now()) @db.DateTime(3)
  updatedAt   DateTime @updatedAt @db.DateTime(3)

  users UserRole[]

  @@map("roles")
}

model UserRole {
  id         BigInt   @id @default(autoincrement())
  userId     BigInt
  roleId     Int
  assignedAt DateTime @default(now()) @db.DateTime(3)
  assignedBy BigInt?

  user User @relation(fields: [userId], references: [id], onDelete: Cascade)
  role Role @relation(fields: [roleId], references: [id], onDelete: Cascade)

  @@unique([userId, roleId])
  @@index([roleId])
  @@index([assignedBy])
  @@map("user_roles")
}

model Customer {
  id           BigInt    @id @default(autoincrement())
  publicId     String    @unique @db.VarChar(36)
  userId       BigInt    @unique
  firstName    String    @db.VarChar(100)
  middleName   String?   @db.VarChar(100)
  lastName     String?   @db.VarChar(100)
  gender       Gender?
  dateOfBirth  DateTime? @db.Date
  profilePhoto String?   @db.VarChar(500)
  createdAt    DateTime  @default(now()) @db.DateTime(3)
  updatedAt    DateTime  @updatedAt @db.DateTime(3)

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

  @@index([firstName, lastName])
  @@map("customers")
}

model Driver {
  id              BigInt       @id @default(autoincrement())
  publicId        String       @unique @db.VarChar(36)
  driverCode      String       @unique @db.VarChar(40)
  userId          BigInt       @unique
  firstName       String       @db.VarChar(100)
  middleName      String?      @db.VarChar(100)
  lastName        String?      @db.VarChar(100)
  gender          Gender?
  dateOfBirth     DateTime?    @db.Date
  emergencyName   String?      @db.VarChar(150)
  emergencyMobile String?      @db.VarChar(20)
  status          DriverStatus @default(REGISTERED)
  isOnline        Boolean      @default(false)
  approvedAt      DateTime?    @db.DateTime(3)
  createdAt       DateTime     @default(now()) @db.DateTime(3)
  updatedAt       DateTime     @updatedAt @db.DateTime(3)

  user           User             @relation(fields: [userId], references: [id], onDelete: Cascade)
  kyc            DriverKyc?
  vehicles       Vehicle[]
  documents      DriverDocument[]
  bookings       Booking[]        @relation("AssignedDriverBookings")
  offers         DriverOffer[]
  trips          Trip[]
  locationEvents LocationEvent[]
  commissions    Commission[]
  settlements    Settlement[]

  @@index([status])
  @@index([isOnline])
  @@index([createdAt])
  @@map("drivers")
}

model DriverKyc {
  id                   BigInt    @id @default(autoincrement())
  driverId             BigInt    @unique
  status               KycStatus @default(NOT_SUBMITTED)
  aadhaarLast4         String?   @db.Char(4)
  panMasked            String?   @db.VarChar(20)
  drivingLicenseMasked String?   @db.VarChar(30)
  submittedAt          DateTime? @db.DateTime(3)
  reviewedAt           DateTime? @db.DateTime(3)
  reviewedBy           BigInt?
  rejectionReason      String?   @db.VarChar(500)
  createdAt            DateTime  @default(now()) @db.DateTime(3)
  updatedAt            DateTime  @updatedAt @db.DateTime(3)

  driver Driver @relation(fields: [driverId], references: [id], onDelete: Cascade)

  @@index([status])
  @@index([reviewedBy])
  @@map("driver_kyc")
}

model Vehicle {
  id              BigInt        @id @default(autoincrement())
  publicId        String        @unique @db.VarChar(36)
  driverId        BigInt
  registrationNo  String        @unique @db.VarChar(30)
  vehicleType     VehicleType
  make            String?       @db.VarChar(100)
  model           String?       @db.VarChar(100)
  variant         String?       @db.VarChar(100)
  color           String?       @db.VarChar(50)
  manufactureYear Int?
  seatingCapacity Int?
  status          VehicleStatus @default(PENDING)
  isPrimary       Boolean       @default(false)
  approvedAt      DateTime?     @db.DateTime(3)
  createdAt       DateTime      @default(now()) @db.DateTime(3)
  updatedAt       DateTime      @updatedAt @db.DateTime(3)

  driver   Driver    @relation(fields: [driverId], references: [id], onDelete: Cascade)
  bookings Booking[] @relation("AssignedVehicleBookings")
  trips    Trip[]

  @@index([driverId, status])
  @@index([vehicleType])
  @@map("vehicles")
}

model DriverDocument {
  id               BigInt         @id @default(autoincrement())
  publicId         String         @unique @db.VarChar(36)
  driverId         BigInt
  documentType     DocumentType
  documentNoMasked String?        @db.VarChar(100)
  filePath         String         @db.VarChar(500)
  status           DocumentStatus @default(PENDING)
  expiresAt        DateTime?      @db.Date
  verifiedAt       DateTime?      @db.DateTime(3)
  verifiedBy       BigInt?
  rejectionReason  String?        @db.VarChar(500)
  createdAt        DateTime       @default(now()) @db.DateTime(3)
  updatedAt        DateTime       @updatedAt @db.DateTime(3)

  driver Driver @relation(fields: [driverId], references: [id], onDelete: Cascade)

  @@index([driverId, documentType])
  @@index([status])
  @@index([expiresAt])
  @@map("driver_documents")
}

model AuditLog {
  id           BigInt   @id @default(autoincrement())
  publicId     String   @unique @db.VarChar(36)
  actorUserId  BigInt?
  action       String   @db.VarChar(120)
  entityType   String   @db.VarChar(120)
  entityId     String?  @db.VarChar(191)
  ipAddress    String?  @db.VarChar(64)
  userAgent    String?  @db.VarChar(500)
  metadataJson Json?
  createdAt    DateTime @default(now()) @db.DateTime(3)

  @@index([actorUserId])
  @@index([entityType, entityId])
  @@index([action])
  @@index([createdAt])
  @@map("audit_logs")
}

enum ServiceZoneStatus {
  ACTIVE
  INACTIVE
}

enum VehicleCategoryStatus {
  ACTIVE
  INACTIVE
}

enum FareRuleStatus {
  ACTIVE
  INACTIVE
}

enum FareRuleType {
  STANDARD
  AIRPORT
  RENTAL
  OUTSTATION
}

model ServiceZone {
  id        BigInt            @id @default(autoincrement())
  publicId  String            @unique @db.VarChar(36)
  code      String            @unique @db.VarChar(50)
  name      String            @db.VarChar(150)
  city      String            @db.VarChar(120)
  state     String            @db.VarChar(120)
  country   String            @default("India") @db.VarChar(100)
  centerLat Decimal?          @db.Decimal(10, 7)
  centerLng Decimal?          @db.Decimal(10, 7)
  radiusKm  Decimal?          @db.Decimal(8, 2)
  timezone  String            @default("Asia/Kolkata") @db.VarChar(80)
  status    ServiceZoneStatus @default(ACTIVE)
  createdAt DateTime          @default(now()) @db.DateTime(3)
  updatedAt DateTime          @updatedAt @db.DateTime(3)

  fareRules FareRule[]
  bookings  Booking[]

  @@index([city, state])
  @@index([status])
  @@map("service_zones")
}

model VehicleCategory {
  id              BigInt                @id @default(autoincrement())
  publicId        String                @unique @db.VarChar(36)
  code            String                @unique @db.VarChar(40)
  name            String                @db.VarChar(100)
  description     String?               @db.VarChar(255)
  vehicleType     VehicleType
  seatingCapacity Int?
  sortOrder       Int                   @default(0)
  iconUrl         String?               @db.VarChar(500)
  status          VehicleCategoryStatus @default(ACTIVE)
  createdAt       DateTime              @default(now()) @db.DateTime(3)
  updatedAt       DateTime              @updatedAt @db.DateTime(3)

  fareRules FareRule[]
  bookings  Booking[]

  @@index([vehicleType])
  @@index([status, sortOrder])
  @@map("vehicle_categories")
}

model FareRule {
  id                BigInt       @id @default(autoincrement())
  publicId          String       @unique @db.VarChar(36)
  serviceZoneId     BigInt
  vehicleCategoryId BigInt
  ruleType          FareRuleType @default(STANDARD)

  baseFare       Decimal @db.Decimal(12, 2)
  baseDistanceKm Decimal @default(0) @db.Decimal(8, 2)
  perKmRate      Decimal @db.Decimal(12, 2)
  perMinuteRate  Decimal @default(0) @db.Decimal(12, 2)
  minimumFare    Decimal @db.Decimal(12, 2)

  bookingFee         Decimal @default(0) @db.Decimal(12, 2)
  waitingFreeMinutes Int     @default(0)
  waitingPerMinute   Decimal @default(0) @db.Decimal(12, 2)

  cancellationFee Decimal @default(0) @db.Decimal(12, 2)
  driverAllowance Decimal @default(0) @db.Decimal(12, 2)

  nightChargePercent Decimal @default(0) @db.Decimal(6, 2)
  surgeMultiplierMax Decimal @default(1) @db.Decimal(6, 2)

  taxPercent Decimal @default(0) @db.Decimal(6, 2)

  effectiveFrom DateTime       @db.DateTime(3)
  effectiveTo   DateTime?      @db.DateTime(3)
  status        FareRuleStatus @default(ACTIVE)

  createdAt DateTime @default(now()) @db.DateTime(3)
  updatedAt DateTime @updatedAt @db.DateTime(3)

  serviceZone     ServiceZone     @relation(fields: [serviceZoneId], references: [id], onDelete: Restrict)
  vehicleCategory VehicleCategory @relation(fields: [vehicleCategoryId], references: [id], onDelete: Restrict)

  @@index([serviceZoneId, vehicleCategoryId, status])
  @@index([ruleType])
  @@index([effectiveFrom, effectiveTo])
  @@map("fare_rules")
}

enum BookingType {
  INSTANT
  SCHEDULED
  RENTAL
  OUTSTATION_ONE_WAY
  OUTSTATION_ROUND_TRIP
  AIRPORT
  MULTI_STOP
}

enum BookingStatus {
  REQUESTED
  SEARCHING_DRIVER
  DRIVER_ASSIGNED
  DRIVER_EN_ROUTE
  DRIVER_ARRIVED
  OTP_VERIFIED
  TRIP_STARTED
  TRIP_COMPLETED
  PAYMENT_PENDING
  PAID
  CLOSED
  CANCELLED
  NO_DRIVER_AVAILABLE
  PAYMENT_FAILED
}

enum BookingStopType {
  PICKUP
  WAYPOINT
  DROP
}

enum DriverOfferStatus {
  PENDING
  ACCEPTED
  REJECTED
  EXPIRED
  CANCELLED
}

enum TripStatus {
  CREATED
  DRIVER_EN_ROUTE
  DRIVER_ARRIVED
  OTP_VERIFIED
  STARTED
  COMPLETED
  CANCELLED
}

enum LocationEventType {
  DRIVER_ONLINE
  DRIVER_OFFLINE
  DRIVER_LOCATION
  BOOKING_ASSIGNED
  EN_ROUTE
  ARRIVED
  TRIP_STARTED
  TRIP_LOCATION
  TRIP_COMPLETED
}

model Booking {
  id          BigInt @id @default(autoincrement())
  publicId    String @unique @db.VarChar(36)
  bookingCode String @unique @db.VarChar(40)

  customerUserId    BigInt
  serviceZoneId     BigInt
  vehicleCategoryId BigInt
  assignedDriverId  BigInt?
  assignedVehicleId BigInt?

  bookingType BookingType   @default(INSTANT)
  status      BookingStatus @default(REQUESTED)

  pickupAddress String  @db.VarChar(500)
  pickupLat     Decimal @db.Decimal(10, 7)
  pickupLng     Decimal @db.Decimal(10, 7)

  dropAddress String?  @db.VarChar(500)
  dropLat     Decimal? @db.Decimal(10, 7)
  dropLng     Decimal? @db.Decimal(10, 7)

  estimatedDistanceKm  Decimal? @db.Decimal(10, 2)
  estimatedDurationMin Int?
  estimatedFare        Decimal? @db.Decimal(12, 2)
  finalFare            Decimal? @db.Decimal(12, 2)
  currency             String   @default("INR") @db.Char(3)

  scheduledAt      DateTime? @db.DateTime(3)
  requestedAt      DateTime  @default(now()) @db.DateTime(3)
  driverAssignedAt DateTime? @db.DateTime(3)
  driverArrivedAt  DateTime? @db.DateTime(3)
  cancelledAt      DateTime? @db.DateTime(3)
  completedAt      DateTime? @db.DateTime(3)

  cancellationReason String? @db.VarChar(500)
  customerNote       String? @db.VarChar(500)

  createdAt DateTime @default(now()) @db.DateTime(3)
  updatedAt DateTime @updatedAt @db.DateTime(3)

  customerUser    User            @relation("CustomerUserBookings", fields: [customerUserId], references: [id], onDelete: Restrict)
  serviceZone     ServiceZone     @relation(fields: [serviceZoneId], references: [id], onDelete: Restrict)
  vehicleCategory VehicleCategory @relation(fields: [vehicleCategoryId], references: [id], onDelete: Restrict)

  assignedDriver  Driver?  @relation("AssignedDriverBookings", fields: [assignedDriverId], references: [id], onDelete: SetNull)
  assignedVehicle Vehicle? @relation("AssignedVehicleBookings", fields: [assignedVehicleId], references: [id], onDelete: SetNull)

  stops             BookingStop[]
  driverOffers      DriverOffer[]
  trip              Trip?
  payments          Payment[]
  commissions       Commission[]
  couponRedemptions CouponRedemption[]
  ratings           Rating[]
  supportTickets    SupportTicket[]
  emergencyEvents   EmergencyEvent[]

  @@index([customerUserId, createdAt])
  @@index([status, requestedAt])
  @@index([serviceZoneId, status])
  @@index([vehicleCategoryId, status])
  @@index([assignedDriverId, status])
  @@index([scheduledAt])
  @@map("bookings")
}

model BookingStop {
  id         BigInt          @id @default(autoincrement())
  publicId   String          @unique @db.VarChar(36)
  bookingId  BigInt
  stopType   BookingStopType
  sequenceNo Int
  address    String          @db.VarChar(500)
  latitude   Decimal         @db.Decimal(10, 7)
  longitude  Decimal         @db.Decimal(10, 7)
  reachedAt  DateTime?       @db.DateTime(3)
  createdAt  DateTime        @default(now()) @db.DateTime(3)
  updatedAt  DateTime        @updatedAt @db.DateTime(3)

  booking Booking @relation(fields: [bookingId], references: [id], onDelete: Cascade)

  @@unique([bookingId, sequenceNo])
  @@index([bookingId, stopType])
  @@map("booking_stops")
}

model DriverOffer {
  id          BigInt            @id @default(autoincrement())
  publicId    String            @unique @db.VarChar(36)
  bookingId   BigInt
  driverId    BigInt
  status      DriverOfferStatus @default(PENDING)
  offeredAt   DateTime          @default(now()) @db.DateTime(3)
  expiresAt   DateTime          @db.DateTime(3)
  respondedAt DateTime?         @db.DateTime(3)
  distanceKm  Decimal?          @db.Decimal(10, 2)
  etaMinutes  Int?
  createdAt   DateTime          @default(now()) @db.DateTime(3)
  updatedAt   DateTime          @updatedAt @db.DateTime(3)

  booking Booking @relation(fields: [bookingId], references: [id], onDelete: Cascade)
  driver  Driver  @relation(fields: [driverId], references: [id], onDelete: Cascade)

  @@unique([bookingId, driverId])
  @@index([driverId, status, expiresAt])
  @@index([bookingId, status])
  @@map("driver_offers")
}

model Trip {
  id        BigInt     @id @default(autoincrement())
  publicId  String     @unique @db.VarChar(36)
  tripCode  String     @unique @db.VarChar(40)
  bookingId BigInt     @unique
  driverId  BigInt
  vehicleId BigInt
  status    TripStatus @default(CREATED)

  startOtpHash  String?   @db.VarChar(255)
  otpExpiresAt  DateTime? @db.DateTime(3)
  otpVerifiedAt DateTime? @db.DateTime(3)

  startLat Decimal? @db.Decimal(10, 7)
  startLng Decimal? @db.Decimal(10, 7)
  endLat   Decimal? @db.Decimal(10, 7)
  endLng   Decimal? @db.Decimal(10, 7)

  actualDistanceKm  Decimal? @db.Decimal(10, 2)
  actualDurationMin Int?

  startedAt   DateTime? @db.DateTime(3)
  completedAt DateTime? @db.DateTime(3)
  cancelledAt DateTime? @db.DateTime(3)

  createdAt DateTime @default(now()) @db.DateTime(3)
  updatedAt DateTime @updatedAt @db.DateTime(3)

  booking         Booking          @relation(fields: [bookingId], references: [id], onDelete: Restrict)
  driver          Driver           @relation(fields: [driverId], references: [id], onDelete: Restrict)
  vehicle         Vehicle          @relation(fields: [vehicleId], references: [id], onDelete: Restrict)
  locationEvents  LocationEvent[]
  ratings         Rating[]
  emergencyEvents EmergencyEvent[]

  @@index([driverId, status])
  @@index([status, createdAt])
  @@map("trips")
}

model LocationEvent {
  id         BigInt            @id @default(autoincrement())
  publicId   String            @unique @db.VarChar(36)
  driverId   BigInt
  tripId     BigInt?
  eventType  LocationEventType
  latitude   Decimal           @db.Decimal(10, 7)
  longitude  Decimal           @db.Decimal(10, 7)
  heading    Decimal?          @db.Decimal(6, 2)
  speedKph   Decimal?          @db.Decimal(8, 2)
  accuracyM  Decimal?          @db.Decimal(8, 2)
  recordedAt DateTime          @db.DateTime(3)
  createdAt  DateTime          @default(now()) @db.DateTime(3)

  driver Driver @relation(fields: [driverId], references: [id], onDelete: Cascade)
  trip   Trip?  @relation(fields: [tripId], references: [id], onDelete: Cascade)

  @@index([driverId, recordedAt])
  @@index([tripId, recordedAt])
  @@index([eventType, recordedAt])
  @@map("location_events")
}

enum PaymentMethod {
  CASH
  UPI
  CARD
  NET_BANKING
  WALLET
  PAYMENT_GATEWAY
}

enum PaymentStatus {
  CREATED
  PENDING
  AUTHORIZED
  CAPTURED
  SUCCESS
  FAILED
  CANCELLED
  PARTIALLY_REFUNDED
  REFUNDED
}

enum RefundStatus {
  CREATED
  PENDING
  PROCESSING
  SUCCESS
  FAILED
  CANCELLED
}

enum WalletOwnerType {
  CUSTOMER
  DRIVER
}

enum WalletTransactionType {
  CREDIT
  DEBIT
}

enum WalletTransactionReason {
  RIDE_PAYMENT
  RIDE_EARNING
  REFUND
  COMMISSION
  SETTLEMENT
  ADJUSTMENT
  PROMOTION
  CANCELLATION
  OTHER
}

enum CommissionStatus {
  PENDING
  CALCULATED
  SETTLED
  WAIVED
  REVERSED
}

enum SettlementStatus {
  CREATED
  PENDING
  PROCESSING
  SUCCESS
  FAILED
  CANCELLED
}

model Payment {
  id             BigInt @id @default(autoincrement())
  publicId       String @unique @db.VarChar(36)
  paymentCode    String @unique @db.VarChar(50)
  bookingId      BigInt
  customerUserId BigInt

  method PaymentMethod
  status PaymentStatus @default(CREATED)

  amount   Decimal @db.Decimal(14, 2)
  currency String  @default("INR") @db.Char(3)

  gatewayProvider  String? @db.VarChar(80)
  gatewayOrderId   String? @db.VarChar(191)
  gatewayPaymentId String? @db.VarChar(191)
  gatewayReference String? @db.VarChar(191)
  idempotencyKey   String? @unique @db.VarChar(191)

  failureCode    String? @db.VarChar(100)
  failureMessage String? @db.VarChar(500)

  authorizedAt DateTime? @db.DateTime(3)
  capturedAt   DateTime? @db.DateTime(3)
  paidAt       DateTime? @db.DateTime(3)
  failedAt     DateTime? @db.DateTime(3)

  createdAt DateTime @default(now()) @db.DateTime(3)
  updatedAt DateTime @updatedAt @db.DateTime(3)

  booking      Booking  @relation(fields: [bookingId], references: [id], onDelete: Restrict)
  customerUser User     @relation(fields: [customerUserId], references: [id], onDelete: Restrict)
  refunds      Refund[]

  @@index([bookingId, status])
  @@index([customerUserId, createdAt])
  @@index([gatewayProvider, gatewayOrderId])
  @@index([gatewayProvider, gatewayPaymentId])
  @@index([status, createdAt])
  @@map("payments")
}

model Refund {
  id         BigInt @id @default(autoincrement())
  publicId   String @unique @db.VarChar(36)
  refundCode String @unique @db.VarChar(50)
  paymentId  BigInt

  amount   Decimal      @db.Decimal(14, 2)
  currency String       @default("INR") @db.Char(3)
  status   RefundStatus @default(CREATED)

  reason String? @db.VarChar(500)

  gatewayRefundId  String? @db.VarChar(191)
  gatewayReference String? @db.VarChar(191)
  idempotencyKey   String? @unique @db.VarChar(191)

  requestedAt DateTime  @default(now()) @db.DateTime(3)
  processedAt DateTime? @db.DateTime(3)
  failedAt    DateTime? @db.DateTime(3)

  createdAt DateTime @default(now()) @db.DateTime(3)
  updatedAt DateTime @updatedAt @db.DateTime(3)

  payment Payment @relation(fields: [paymentId], references: [id], onDelete: Restrict)

  @@index([paymentId, status])
  @@index([status, requestedAt])
  @@map("refunds")
}

model Wallet {
  id        BigInt          @id @default(autoincrement())
  publicId  String          @unique @db.VarChar(36)
  userId    BigInt          @unique
  ownerType WalletOwnerType

  availableBalance Decimal @default(0) @db.Decimal(14, 2)
  pendingBalance   Decimal @default(0) @db.Decimal(14, 2)
  currency         String  @default("INR") @db.Char(3)

  createdAt DateTime @default(now()) @db.DateTime(3)
  updatedAt DateTime @updatedAt @db.DateTime(3)

  user         User                @relation(fields: [userId], references: [id], onDelete: Restrict)
  transactions WalletTransaction[]

  @@index([ownerType])
  @@map("wallets")
}

model WalletTransaction {
  id       BigInt @id @default(autoincrement())
  publicId String @unique @db.VarChar(36)
  walletId BigInt

  transactionType WalletTransactionType
  reason          WalletTransactionReason

  amount        Decimal @db.Decimal(14, 2)
  balanceBefore Decimal @db.Decimal(14, 2)
  balanceAfter  Decimal @db.Decimal(14, 2)
  currency      String  @default("INR") @db.Char(3)

  referenceType  String? @db.VarChar(80)
  referenceId    String? @db.VarChar(191)
  idempotencyKey String  @unique @db.VarChar(191)
  description    String? @db.VarChar(500)

  createdAt DateTime @default(now()) @db.DateTime(3)

  wallet Wallet @relation(fields: [walletId], references: [id], onDelete: Restrict)

  @@index([walletId, createdAt])
  @@index([referenceType, referenceId])
  @@map("wallet_transactions")
}

model Commission {
  id        BigInt @id @default(autoincrement())
  publicId  String @unique @db.VarChar(36)
  bookingId BigInt
  driverId  BigInt

  grossFare         Decimal @db.Decimal(14, 2)
  commissionPercent Decimal @db.Decimal(6, 2)
  commissionAmount  Decimal @db.Decimal(14, 2)
  taxAmount         Decimal @default(0) @db.Decimal(14, 2)
  driverNetAmount   Decimal @db.Decimal(14, 2)
  currency          String  @default("INR") @db.Char(3)

  status CommissionStatus @default(PENDING)

  calculatedAt DateTime? @db.DateTime(3)
  settledAt    DateTime? @db.DateTime(3)
  createdAt    DateTime  @default(now()) @db.DateTime(3)
  updatedAt    DateTime  @updatedAt @db.DateTime(3)

  booking         Booking          @relation(fields: [bookingId], references: [id], onDelete: Restrict)
  driver          Driver           @relation(fields: [driverId], references: [id], onDelete: Restrict)
  settlementItems SettlementItem[]

  @@unique([bookingId, driverId])
  @@index([driverId, status])
  @@index([status, createdAt])
  @@map("commissions")
}

model Settlement {
  id             BigInt @id @default(autoincrement())
  publicId       String @unique @db.VarChar(36)
  settlementCode String @unique @db.VarChar(50)
  driverId       BigInt

  grossAmount     Decimal @db.Decimal(14, 2)
  deductionAmount Decimal @default(0) @db.Decimal(14, 2)
  netAmount       Decimal @db.Decimal(14, 2)
  currency        String  @default("INR") @db.Char(3)

  status SettlementStatus @default(CREATED)

  bankReference    String? @db.VarChar(191)
  gatewayReference String? @db.VarChar(191)
  idempotencyKey   String? @unique @db.VarChar(191)

  periodStart DateTime? @db.DateTime(3)
  periodEnd   DateTime? @db.DateTime(3)

  initiatedAt DateTime? @db.DateTime(3)
  processedAt DateTime? @db.DateTime(3)
  failedAt    DateTime? @db.DateTime(3)

  createdAt DateTime @default(now()) @db.DateTime(3)
  updatedAt DateTime @updatedAt @db.DateTime(3)

  driver Driver           @relation(fields: [driverId], references: [id], onDelete: Restrict)
  items  SettlementItem[]

  @@index([driverId, status])
  @@index([status, createdAt])
  @@map("settlements")
}

model SettlementItem {
  id           BigInt   @id @default(autoincrement())
  publicId     String   @unique @db.VarChar(36)
  settlementId BigInt
  commissionId BigInt   @unique
  amount       Decimal  @db.Decimal(14, 2)
  createdAt    DateTime @default(now()) @db.DateTime(3)

  settlement Settlement @relation(fields: [settlementId], references: [id], onDelete: Restrict)
  commission Commission @relation(fields: [commissionId], references: [id], onDelete: Restrict)

  @@index([settlementId])
  @@map("settlement_items")
}

enum CouponType {
  FLAT
  PERCENTAGE
}

enum CouponStatus {
  ACTIVE
  INACTIVE
  EXPIRED
}

enum SupportTicketStatus {
  OPEN
  IN_PROGRESS
  WAITING_CUSTOMER
  RESOLVED
  CLOSED
}

enum SupportPriority {
  LOW
  NORMAL
  HIGH
  URGENT
}

enum NotificationChannel {
  IN_APP
  PUSH
  SMS
  EMAIL
  WHATSAPP
}

enum NotificationStatus {
  QUEUED
  PROCESSING
  SENT
  DELIVERED
  FAILED
  CANCELLED
}

enum EmergencyType {
  SOS
  ACCIDENT
  MEDICAL
  SAFETY
  VEHICLE_BREAKDOWN
  OTHER
}

enum EmergencyStatus {
  OPEN
  ACKNOWLEDGED
  RESPONDING
  RESOLVED
  CLOSED
}

model Coupon {
  id          BigInt  @id @default(autoincrement())
  publicId    String  @unique @db.VarChar(36)
  code        String  @unique @db.VarChar(50)
  name        String  @db.VarChar(150)
  description String? @db.VarChar(500)

  couponType      CouponType
  discountValue   Decimal    @db.Decimal(12, 2)
  maximumDiscount Decimal?   @db.Decimal(12, 2)
  minimumFare     Decimal    @default(0) @db.Decimal(12, 2)

  totalUsageLimit   Int?
  perUserUsageLimit Int  @default(1)
  usedCount         Int  @default(0)

  validFrom  DateTime     @db.DateTime(3)
  validUntil DateTime     @db.DateTime(3)
  status     CouponStatus @default(ACTIVE)

  createdAt DateTime @default(now()) @db.DateTime(3)
  updatedAt DateTime @updatedAt @db.DateTime(3)

  redemptions CouponRedemption[]

  @@index([status, validFrom, validUntil])
  @@map("coupons")
}

model CouponRedemption {
  id        BigInt @id @default(autoincrement())
  publicId  String @unique @db.VarChar(36)
  couponId  BigInt
  userId    BigInt
  bookingId BigInt

  discountAmount Decimal  @db.Decimal(12, 2)
  redeemedAt     DateTime @default(now()) @db.DateTime(3)

  coupon  Coupon  @relation(fields: [couponId], references: [id], onDelete: Restrict)
  user    User    @relation(fields: [userId], references: [id], onDelete: Restrict)
  booking Booking @relation(fields: [bookingId], references: [id], onDelete: Restrict)

  @@unique([couponId, bookingId])
  @@index([userId, redeemedAt])
  @@index([couponId, userId])
  @@map("coupon_redemptions")
}

model Rating {
  id               BigInt  @id @default(autoincrement())
  publicId         String  @unique @db.VarChar(36)
  bookingId        BigInt
  tripId           BigInt?
  givenByUserId    BigInt
  receivedByUserId BigInt

  score     Int
  comment   String?  @db.VarChar(1000)
  createdAt DateTime @default(now()) @db.DateTime(3)
  updatedAt DateTime @updatedAt @db.DateTime(3)

  booking Booking @relation(fields: [bookingId], references: [id], onDelete: Restrict)
  trip    Trip?   @relation(fields: [tripId], references: [id], onDelete: Restrict)

  givenBy    User @relation("RatingGivenBy", fields: [givenByUserId], references: [id], onDelete: Restrict)
  receivedBy User @relation("RatingReceivedBy", fields: [receivedByUserId], references: [id], onDelete: Restrict)

  @@unique([bookingId, givenByUserId, receivedByUserId])
  @@index([receivedByUserId, createdAt])
  @@index([tripId])
  @@map("ratings")
}

model SupportTicket {
  id              BigInt  @id @default(autoincrement())
  publicId        String  @unique @db.VarChar(36)
  ticketCode      String  @unique @db.VarChar(50)
  requesterUserId BigInt
  bookingId       BigInt?

  subject     String              @db.VarChar(200)
  description String              @db.Text
  status      SupportTicketStatus @default(OPEN)
  priority    SupportPriority     @default(NORMAL)

  assignedToUserId BigInt?
  resolvedAt       DateTime? @db.DateTime(3)
  closedAt         DateTime? @db.DateTime(3)

  createdAt DateTime @default(now()) @db.DateTime(3)
  updatedAt DateTime @updatedAt @db.DateTime(3)

  requester User             @relation("SupportTicketRequester", fields: [requesterUserId], references: [id], onDelete: Restrict)
  booking   Booking?         @relation(fields: [bookingId], references: [id], onDelete: SetNull)
  messages  SupportMessage[]

  @@index([requesterUserId, createdAt])
  @@index([bookingId])
  @@index([status, priority, createdAt])
  @@index([assignedToUserId])
  @@map("support_tickets")
}

model SupportMessage {
  id             BigInt   @id @default(autoincrement())
  publicId       String   @unique @db.VarChar(36)
  ticketId       BigInt
  authorUserId   BigInt
  message        String   @db.Text
  isInternalNote Boolean  @default(false)
  createdAt      DateTime @default(now()) @db.DateTime(3)

  ticket SupportTicket @relation(fields: [ticketId], references: [id], onDelete: Cascade)
  author User          @relation("SupportMessageAuthor", fields: [authorUserId], references: [id], onDelete: Restrict)

  @@index([ticketId, createdAt])
  @@index([authorUserId])
  @@map("support_messages")
}

model Notification {
  id       BigInt              @id @default(autoincrement())
  publicId String              @unique @db.VarChar(36)
  userId   BigInt
  channel  NotificationChannel
  status   NotificationStatus  @default(QUEUED)

  templateCode String? @db.VarChar(100)
  subject      String? @db.VarChar(255)
  body         String  @db.Text

  destination       String? @db.VarChar(255)
  provider          String? @db.VarChar(100)
  providerMessageId String? @db.VarChar(191)

  idempotencyKey String? @unique @db.VarChar(191)

  queuedAt       DateTime  @default(now()) @db.DateTime(3)
  sentAt         DateTime? @db.DateTime(3)
  deliveredAt    DateTime? @db.DateTime(3)
  failedAt       DateTime? @db.DateTime(3)
  failureMessage String?   @db.VarChar(500)

  createdAt DateTime @default(now()) @db.DateTime(3)
  updatedAt DateTime @updatedAt @db.DateTime(3)

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

  @@index([userId, createdAt])
  @@index([status, queuedAt])
  @@index([channel, status])
  @@map("notifications")
}

model EmergencyEvent {
  id            BigInt @id @default(autoincrement())
  publicId      String @unique @db.VarChar(36)
  emergencyCode String @unique @db.VarChar(50)

  raisedByUserId BigInt
  bookingId      BigInt?
  tripId         BigInt?

  emergencyType EmergencyType
  status        EmergencyStatus @default(OPEN)

  latitude  Decimal? @db.Decimal(10, 7)
  longitude Decimal? @db.Decimal(10, 7)

  description String? @db.VarChar(1000)

  acknowledgedByUserId BigInt?
  acknowledgedAt       DateTime? @db.DateTime(3)
  resolvedAt           DateTime? @db.DateTime(3)
  resolutionNote       String?   @db.VarChar(1000)

  createdAt DateTime @default(now()) @db.DateTime(3)
  updatedAt DateTime @updatedAt @db.DateTime(3)

  raisedBy User     @relation("EmergencyRaisedBy", fields: [raisedByUserId], references: [id], onDelete: Restrict)
  booking  Booking? @relation(fields: [bookingId], references: [id], onDelete: SetNull)
  trip     Trip?    @relation(fields: [tripId], references: [id], onDelete: SetNull)

  @@index([raisedByUserId, createdAt])
  @@index([bookingId])
  @@index([tripId])
  @@index([status, emergencyType, createdAt])
  @@index([acknowledgedByUserId])
  @@map("emergency_events")
}

enum OtpPurpose {
  LOGIN
  REGISTRATION
  VERIFY_MOBILE
  VERIFY_EMAIL
  RESET_PASSWORD
  CHANGE_MOBILE
  CHANGE_EMAIL
  TRIP_START
}

enum OtpChannel {
  SMS
  EMAIL
  WHATSAPP
}

enum OtpStatus {
  CREATED
  SENT
  VERIFIED
  EXPIRED
  FAILED
  CANCELLED
  LOCKED
}

enum AuthSessionStatus {
  ACTIVE
  REVOKED
  EXPIRED
}

enum LoginAttemptResult {
  SUCCESS
  INVALID_CREDENTIALS
  OTP_REQUIRED
  OTP_FAILED
  BLOCKED
  RATE_LIMITED
  USER_NOT_FOUND
}

model OtpChallenge {
  id       BigInt @id @default(autoincrement())
  publicId String @unique @db.VarChar(36)

  userId  BigInt?
  purpose OtpPurpose
  channel OtpChannel
  status  OtpStatus  @default(CREATED)

  destinationHash String @db.VarChar(255)
  otpHash         String @db.VarChar(255)

  attemptCount Int @default(0)
  maxAttempts  Int @default(5)

  expiresAt  DateTime  @db.DateTime(3)
  verifiedAt DateTime? @db.DateTime(3)
  sentAt     DateTime? @db.DateTime(3)

  requestIp String? @db.VarChar(64)
  userAgent String? @db.VarChar(500)

  createdAt DateTime @default(now()) @db.DateTime(3)
  updatedAt DateTime @updatedAt @db.DateTime(3)

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

  @@index([userId, purpose, status])
  @@index([destinationHash, purpose, status])
  @@index([expiresAt])
  @@index([createdAt])
  @@map("otp_challenges")
}

model AuthSession {
  id       BigInt @id @default(autoincrement())
  publicId String @unique @db.VarChar(36)
  userId   BigInt

  sessionTokenHash String            @unique @db.VarChar(255)
  status           AuthSessionStatus @default(ACTIVE)

  ipAddress  String? @db.VarChar(64)
  userAgent  String? @db.VarChar(500)
  deviceId   String? @db.VarChar(191)
  deviceName String? @db.VarChar(191)

  lastSeenAt DateTime? @db.DateTime(3)
  expiresAt  DateTime  @db.DateTime(3)
  revokedAt  DateTime? @db.DateTime(3)

  createdAt DateTime @default(now()) @db.DateTime(3)
  updatedAt DateTime @updatedAt @db.DateTime(3)

  user          User           @relation(fields: [userId], references: [id], onDelete: Cascade)
  refreshTokens RefreshToken[]

  @@index([userId, status])
  @@index([expiresAt])
  @@index([deviceId])
  @@map("auth_sessions")
}

model RefreshToken {
  id        BigInt @id @default(autoincrement())
  publicId  String @unique @db.VarChar(36)
  sessionId BigInt

  tokenHash String @unique @db.VarChar(255)

  expiresAt    DateTime  @db.DateTime(3)
  consumedAt   DateTime? @db.DateTime(3)
  revokedAt    DateTime? @db.DateTime(3)
  replacedById BigInt?

  createdAt DateTime @default(now()) @db.DateTime(3)

  session AuthSession @relation(fields: [sessionId], references: [id], onDelete: Cascade)

  @@index([sessionId, expiresAt])
  @@index([revokedAt])
  @@index([replacedById])
  @@map("refresh_tokens")
}

model LoginAttempt {
  id       BigInt  @id @default(autoincrement())
  publicId String  @unique @db.VarChar(36)
  userId   BigInt?

  identifierHash String             @db.VarChar(255)
  result         LoginAttemptResult

  ipAddress String? @db.VarChar(64)
  userAgent String? @db.VarChar(500)

  createdAt DateTime @default(now()) @db.DateTime(3)

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

  @@index([userId, createdAt])
  @@index([identifierHash, createdAt])
  @@index([ipAddress, createdAt])
  @@index([result, createdAt])
  @@map("login_attempts")
}
