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

generator client {
  provider      = "prisma-client-js"
  output        = "../prisma-client"
  binaryTargets = ["native", "linux-musl", "linux-musl-openssl-3.0.x", "debian-openssl-1.1.x", "debian-openssl-3.0.x", "rhel-openssl-1.0.x", "rhel-openssl-3.0.x"]
}

model Role {
  id          String    @id @default(uuid()) @db.Uuid
  name        String    @unique
  description String?
  createdAt   DateTime  @default(now()) @map("created_at")
  updatedAt   DateTime  @updatedAt @map("updated_at")
  deletedAt   DateTime? @map("deleted_at")
  createdBy   String?   @map("created_by") @db.Uuid
  updatedBy   String?   @map("updated_by") @db.Uuid

  users       User[]

  @@map("roles")
}

model Permission {
  id          String    @id @default(uuid()) @db.Uuid
  name        String    @unique
  description String?
  createdAt   DateTime  @default(now()) @map("created_at")
  updatedAt   DateTime  @updatedAt @map("updated_at")
  deletedAt   DateTime? @map("deleted_at")
  createdBy   String?   @map("created_by") @db.Uuid
  updatedBy   String?   @map("updated_by") @db.Uuid

  @@map("permissions")
}

model User {
  id           String    @id @default(uuid()) @db.Uuid
  email        String    @unique
  name         String
  passwordHash String    @map("password_hash")
  roleId       String    @map("role_id") @db.Uuid
  status       String    @default("ACTIVE") // ACTIVE, SUSPENDED, DELETED
  createdAt    DateTime  @default(now()) @map("created_at")
  updatedAt    DateTime  @updatedAt @map("updated_at")
  deletedAt    DateTime? @map("deleted_at")
  createdBy    String?   @map("created_by") @db.Uuid
  updatedBy    String?   @map("updated_by") @db.Uuid

  role         Role      @relation(fields: [roleId], references: [id])
  apiTokens    ApiToken[]
  tickets      SupportTicket[]

  @@map("users")
}

model ApiToken {
  id        String    @id @default(uuid()) @db.Uuid
  name      String
  tokenHash String    @unique @map("token_hash")
  userId    String    @map("user_id") @db.Uuid
  status    String    @default("ACTIVE") // ACTIVE, REVOKED
  expiresAt DateTime? @map("expires_at")
  createdAt DateTime  @default(now()) @map("created_at")
  updatedAt DateTime  @updatedAt @map("updated_at")
  deletedAt DateTime? @map("deleted_at")
  createdBy String?   @map("created_by") @db.Uuid
  updatedBy String?   @map("updated_by") @db.Uuid

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

  @@map("api_tokens")
}

model Company {
  id        String    @id @default(uuid()) @db.Uuid
  name      String
  taxNumber String?   @map("tax_number")
  address   String?
  website   String?
  status    String    @default("ACTIVE") // ACTIVE, INACTIVE
  createdAt DateTime  @default(now()) @map("created_at")
  updatedAt DateTime  @updatedAt @map("updated_at")
  deletedAt DateTime? @map("deleted_at")
  createdBy String?   @map("created_by") @db.Uuid
  updatedBy String?   @map("updated_by") @db.Uuid

  customers Customer[]
  licenses  License[]

  @@map("companies")
}

model Customer {
  id        String    @id @default(uuid()) @db.Uuid
  name      String
  email     String    @unique
  phone     String?
  companyId String?   @map("company_id") @db.Uuid
  status    String    @default("ACTIVE") // ACTIVE, SUSPENDED
  createdAt DateTime  @default(now()) @map("created_at")
  updatedAt DateTime  @updatedAt @map("updated_at")
  deletedAt DateTime? @map("deleted_at")
  createdBy String?   @map("created_by") @db.Uuid
  updatedBy String?   @map("updated_by") @db.Uuid

  company       Company?       @relation(fields: [companyId], references: [id])
  licenses      License[]
  subscriptions Subscription[]
  invoices      Invoice[]
  trials        Trial[]
  downloads     Download[]
  tickets       SupportTicket[]

  @@map("customers")
}

model Product {
  id          String    @id @default(uuid()) @db.Uuid
  name        String
  code        String    @unique // e.g. SM-POS, ERP
  description String?
  status      String    @default("ACTIVE") // ACTIVE, ARCHIVED
  createdAt   DateTime  @default(now()) @map("created_at")
  updatedAt   DateTime  @updatedAt @map("updated_at")
  deletedAt   DateTime? @map("deleted_at")
  createdBy   String?   @map("created_by") @db.Uuid
  updatedBy   String?   @map("updated_by") @db.Uuid

  versions ProductVersion[]
  licenses License[]
  trials   Trial[]

  @@map("products")
}

model ProductVersion {
  id                 String    @id @default(uuid()) @db.Uuid
  productId          String    @map("product_id") @db.Uuid
  versionStr         String    @map("version_str")
  releaseNotes       String?   @map("release_notes")
  downloadUrl        String?   @map("download_url")
  checksum           String?
  signature          String?
  minRequiredVersion String?   @map("min_required_version")
  isMandatory        Boolean   @default(false) @map("is_mandatory")
  isBeta             Boolean   @default(false) @map("is_beta")
  createdAt          DateTime  @default(now()) @map("created_at")
  updatedAt          DateTime  @updatedAt @map("updated_at")
  deletedAt          DateTime? @map("deleted_at")
  createdBy          String?   @map("created_by") @db.Uuid
  updatedBy          String?   @map("updated_by") @db.Uuid

  product   Product    @relation(fields: [productId], references: [id])
  updates   Update[]
  downloads Download[]

  @@map("product_versions")
}

model LicenseType {
  id          String    @id @default(uuid()) @db.Uuid
  name        String    @unique // Perpetual, Subscription, Trial, OEM, Partner, etc.
  description String?
  createdAt   DateTime  @default(now()) @map("created_at")
  updatedAt   DateTime  @updatedAt @map("updated_at")
  deletedAt   DateTime? @map("deleted_at")
  createdBy   String?   @map("created_by") @db.Uuid
  updatedBy   String?   @map("updated_by") @db.Uuid

  licenses License[]

  @@map("license_types")
}

model License {
  id                 String    @id @default(uuid()) @db.Uuid
  key                String    @unique // BS-ERP-XXXXX-XXXXX-XXXXX-XXXXX
  productId          String    @map("product_id") @db.Uuid
  customerId         String    @map("customer_id") @db.Uuid
  companyId          String?   @map("company_id") @db.Uuid
  licenseTypeId      String    @map("license_type_id") @db.Uuid
  edition            String    @default("Standard") // Basic, Professional, Enterprise, Ultimate
  status             String    @default("ACTIVE") // ACTIVE, SUSPENDED, EXPIRED, TERMINATED
  maxDevices         Int       @default(1) @map("max_devices")
  startDate          DateTime  @default(now()) @map("start_date")
  expiryDate         DateTime? @map("expiry_date")
  lastRefreshAt      DateTime? @map("last_refresh_at")
  offlineDaysAllowed Int       @default(30) @map("offline_days_allowed")
  createdAt          DateTime  @default(now()) @map("created_at")
  updatedAt          DateTime  @updatedAt @map("updated_at")
  deletedAt          DateTime? @map("deleted_at")
  createdBy          String?   @map("created_by") @db.Uuid
  updatedBy          String?   @map("updated_by") @db.Uuid

  product            Product             @relation(fields: [productId], references: [id])
  customer           Customer            @relation(fields: [customerId], references: [id])
  company            Company?            @relation(fields: [companyId], references: [id])
  licenseType        LicenseType         @relation(fields: [licenseTypeId], references: [id])
  features           LicenseFeature[]
  activations        LicenseActivation[]
  subscriptions      Subscription[]
  renewals           Renewal[]
  blacklists         BlacklistedLicense[]

  @@map("licenses")
}

model LicenseFeature {
  id          String    @id @default(uuid()) @db.Uuid
  licenseId   String    @map("license_id") @db.Uuid
  featureCode String    @map("feature_code") // INVENTORY, Accounting, etc.
  isEnabled   Boolean   @default(true) @map("is_enabled")
  limitValue  Int?      @map("limit_value") // Null means unlimited
  createdAt   DateTime  @default(now()) @map("created_at")
  updatedAt   DateTime  @updatedAt @map("updated_at")
  deletedAt   DateTime? @map("deleted_at")
  createdBy   String?   @map("created_by") @db.Uuid
  updatedBy   String?   @map("updated_by") @db.Uuid

  license     License   @relation(fields: [licenseId], references: [id])

  @@unique([licenseId, featureCode])
  @@map("license_features")
}

model Device {
  id          String    @id @default(uuid()) @db.Uuid
  machineGuid String    @unique @map("machine_guid")
  hostName    String?   @map("host_name")
  osVersion   String?   @map("os_version")
  ipAddress   String?   @map("ip_address")
  country     String?
  city        String?
  lastOnlineAt DateTime  @default(now()) @map("last_online_at")
  status      String    @default("ACTIVE") // ACTIVE, BANNED
  createdAt   DateTime  @default(now()) @map("created_at")
  updatedAt   DateTime  @updatedAt @map("updated_at")
  deletedAt   DateTime? @map("deleted_at")
  createdBy   String?   @map("created_by") @db.Uuid
  updatedBy   String?   @map("updated_by") @db.Uuid

  fingerprints HardwareFingerprint[]
  activations  LicenseActivation[]

  @@map("devices")
}

model HardwareFingerprint {
  id                  String    @id @default(uuid()) @db.Uuid
  deviceId            String    @map("device_id") @db.Uuid
  motherboardId       String?   @map("motherboard_id")
  cpuId               String?   @map("cpu_id")
  diskId              String?   @map("disk_id")
  macAddress          String?   @map("mac_address")
  windowsInstallationId String? @map("windows_installation_id")
  createdAt           DateTime  @default(now()) @map("created_at")
  updatedAt           DateTime  @updatedAt @map("updated_at")
  deletedAt           DateTime? @map("deleted_at")
  createdBy           String?   @map("created_by") @db.Uuid
  updatedBy           String?   @map("updated_by") @db.Uuid

  device              Device    @relation(fields: [deviceId], references: [id])

  @@map("hardware_fingerprints")
}

model LicenseActivation {
  id              String    @id @default(uuid()) @db.Uuid
  licenseId       String    @map("license_id") @db.Uuid
  deviceId        String    @map("device_id") @db.Uuid
  activationToken String    @map("activation_token")
  activatedAt     DateTime  @default(now()) @map("activated_at")
  ipAddress       String?   @map("ip_address")
  country         String?
  city            String?
  osVersion       String?   @map("os_version")
  appVersion      String?   @map("app_version")
  createdAt       DateTime  @default(now()) @map("created_at")
  updatedAt       DateTime  @updatedAt @map("updated_at")
  deletedAt       DateTime? @map("deleted_at")
  createdBy       String?   @map("created_by") @db.Uuid
  updatedBy       String?   @map("updated_by") @db.Uuid

  license         License   @relation(fields: [licenseId], references: [id])
  device          Device    @relation(fields: [deviceId], references: [id])

  @@map("license_activations")
}

model Subscription {
  id              String    @id @default(uuid()) @db.Uuid
  licenseId       String    @map("license_id") @db.Uuid
  customerId      String    @map("customer_id") @db.Uuid
  status          String    @default("ACTIVE") // ACTIVE, TRIALING, PAST_DUE, CANCELED
  billingPeriod   String    @map("billing_period") // Monthly, Quarterly, Yearly
  nextBillingDate DateTime  @map("next_billing_date")
  price           Float
  createdAt       DateTime  @default(now()) @map("created_at")
  updatedAt       DateTime  @updatedAt @map("updated_at")
  deletedAt       DateTime? @map("deleted_at")
  createdBy       String?   @map("created_by") @db.Uuid
  updatedBy       String?   @map("updated_by") @db.Uuid

  license         License   @relation(fields: [licenseId], references: [id])
  customer        Customer  @relation(fields: [customerId], references: [id])
  invoices        Invoice[]
  renewals        Renewal[]

  @@map("subscriptions")
}

model Invoice {
  id             String    @id @default(uuid()) @db.Uuid
  subscriptionId String?   @map("subscription_id") @db.Uuid
  customerId     String    @map("customer_id") @db.Uuid
  invoiceNumber  String    @unique @map("invoice_number")
  amount         Float
  tax            Float     @default(0.0)
  discount       Float     @default(0.0)
  status         String    @default("UNPAID") // PAID, UNPAID, VOID
  dueDate        DateTime  @map("due_date")
  createdAt      DateTime  @default(now()) @map("created_at")
  updatedAt      DateTime  @updatedAt @map("updated_at")
  deletedAt      DateTime? @map("deleted_at")
  createdBy      String?   @map("created_by") @db.Uuid
  updatedBy      String?   @map("updated_by") @db.Uuid

  subscription   Subscription? @relation(fields: [subscriptionId], references: [id])
  customer       Customer      @relation(fields: [customerId], references: [id])
  payments       Payment[]

  @@map("invoices")
}

model Payment {
  id            String    @id @default(uuid()) @db.Uuid
  invoiceId     String    @map("invoice_id") @db.Uuid
  amount        Float
  transactionId String    @unique @map("transaction_id")
  paymentMethod String    @map("payment_method")
  status        String    @default("SUCCESS") // SUCCESS, FAILED, PENDING
  paidAt        DateTime? @map("paid_at")
  createdAt     DateTime  @default(now()) @map("created_at")
  updatedAt     DateTime  @updatedAt @map("updated_at")
  deletedAt     DateTime? @map("deleted_at")
  createdBy     String?   @map("created_by") @db.Uuid
  updatedBy     String?   @map("updated_by") @db.Uuid

  invoice       Invoice   @relation(fields: [invoiceId], references: [id])

  @@map("payments")
}

model Renewal {
  id             String    @id @default(uuid()) @db.Uuid
  licenseId      String    @map("license_id") @db.Uuid
  subscriptionId String?   @map("subscription_id") @db.Uuid
  previousExpiry DateTime? @map("previous_expiry")
  newExpiry      DateTime  @map("new_expiry")
  transactionId  String?   @map("transaction_id")
  renewedAt      DateTime  @default(now()) @map("renewed_at")
  createdAt      DateTime  @default(now()) @map("created_at")
  updatedAt      DateTime  @updatedAt @map("updated_at")
  deletedAt      DateTime? @map("deleted_at")
  createdBy      String?   @map("created_by") @db.Uuid
  updatedBy      String?   @map("updated_by") @db.Uuid

  license        License       @relation(fields: [licenseId], references: [id])
  subscription   Subscription? @relation(fields: [subscriptionId], references: [id])

  @@map("renewals")
}

model Trial {
  id                   String    @id @default(uuid()) @db.Uuid
  customerId           String    @map("customer_id") @db.Uuid
  productId            String    @map("product_id") @db.Uuid
  startDate            DateTime  @default(now()) @map("start_date")
  endDate              DateTime  @map("end_date")
  convertedToLicenseId String?   @map("converted_to_license_id") @db.Uuid
  createdAt            DateTime  @default(now()) @map("created_at")
  updatedAt            DateTime  @updatedAt @map("updated_at")
  deletedAt            DateTime? @map("deleted_at")
  createdBy            String?   @map("created_by") @db.Uuid
  updatedBy            String?   @map("updated_by") @db.Uuid

  customer             Customer  @relation(fields: [customerId], references: [id])
  product              Product   @relation(fields: [productId], references: [id])

  @@map("trials")
}

model Update {
  id               String    @id @default(uuid()) @db.Uuid
  productVersionId String    @map("product_version_id") @db.Uuid
  deviceId         String?   @map("device_id") @db.Uuid
  downloadTime     DateTime  @default(now()) @map("download_time")
  createdAt        DateTime  @default(now()) @map("created_at")
  updatedAt        DateTime  @updatedAt @map("updated_at")
  deletedAt        DateTime? @map("deleted_at")
  createdBy        String?   @map("created_by") @db.Uuid
  updatedBy        String?   @map("updated_by") @db.Uuid

  productVersion   ProductVersion @relation(fields: [productVersionId], references: [id])

  @@map("updates")
}

model Download {
  id               String    @id @default(uuid()) @db.Uuid
  productVersionId String    @map("product_version_id") @db.Uuid
  customerId       String?   @map("customer_id") @db.Uuid
  ipAddress        String?   @map("ip_address")
  userAgent        String?   @map("user_agent")
  downloadedAt     DateTime  @default(now()) @map("downloaded_at")
  createdAt        DateTime  @default(now()) @map("created_at")
  updatedAt        DateTime  @updatedAt @map("updated_at")
  deletedAt        DateTime? @map("deleted_at")
  createdBy        String?   @map("created_by") @db.Uuid
  updatedBy        String?   @map("updated_by") @db.Uuid

  productVersion   ProductVersion @relation(fields: [productVersionId], references: [id])
  customer         Customer?      @relation(fields: [customerId], references: [id])

  @@map("downloads")
}

model AuditLog {
  id          String    @id @default(uuid()) @db.Uuid
  actorId     String?   @map("actor_id") @db.Uuid
  actionType  String    @map("action_type") // e.g. LOGIN, LICENSE_ACTIVATE, LICENSE_REVOKE
  entityTable String    @map("entity_table") // e.g. licenses
  entityId    String?   @map("entity_id") @db.Uuid
  oldValues   Json?     @map("old_values")
  newValues   Json?     @map("new_values")
  ipAddress   String?   @map("ip_address")
  userAgent   String?   @map("user_agent")
  severity    String    @default("INFO") // INFO, WARNING, ERROR
  timestamp   DateTime  @default(now())
  createdAt   DateTime  @default(now()) @map("created_at")
  updatedAt   DateTime  @updatedAt @map("updated_at")
  deletedAt   DateTime? @map("deleted_at")
  createdBy   String?   @map("created_by") @db.Uuid
  updatedBy   String?   @map("updated_by") @db.Uuid

  @@map("audit_logs")
}

model BlacklistedDevice {
  id            String    @id @default(uuid()) @db.Uuid
  machineGuid   String    @unique @map("machine_guid")
  reason        String?
  blacklistedAt DateTime  @default(now()) @map("blacklisted_at")
  blacklistedBy String?   @map("blacklisted_by") @db.Uuid
  createdAt     DateTime  @default(now()) @map("created_at")
  updatedAt     DateTime  @updatedAt @map("updated_at")
  deletedAt     DateTime? @map("deleted_at")
  createdBy     String?   @map("created_by") @db.Uuid
  updatedBy     String?   @map("updated_by") @db.Uuid

  @@map("blacklisted_devices")
}

model BlacklistedLicense {
  id            String    @id @default(uuid()) @db.Uuid
  licenseId     String    @map("license_id") @db.Uuid
  reason        String?
  blacklistedAt DateTime  @default(now()) @map("blacklisted_at")
  blacklistedBy String?   @map("blacklisted_by") @db.Uuid
  createdAt     DateTime  @default(now()) @map("created_at")
  updatedAt     DateTime  @updatedAt @map("updated_at")
  deletedAt     DateTime? @map("deleted_at")
  createdBy     String?   @map("created_by") @db.Uuid
  updatedBy     String?   @map("updated_by") @db.Uuid

  license       License   @relation(fields: [licenseId], references: [id])

  @@map("blacklisted_licenses")
}

model SupportTicket {
  id               String    @id @default(uuid()) @db.Uuid
  customerId       String    @map("customer_id") @db.Uuid
  title            String
  description      String
  status           String    @default("OPEN") // OPEN, IN_PROGRESS, RESOLVED, CLOSED
  priority         String    @default("MEDIUM") // LOW, MEDIUM, HIGH
  assignedToUserId String?   @map("assigned_to_user_id") @db.Uuid
  createdAt        DateTime  @default(now()) @map("created_at")
  updatedAt        DateTime  @updatedAt @map("updated_at")
  deletedAt        DateTime? @map("deleted_at")
  createdBy        String?   @map("created_by") @db.Uuid
  updatedBy        String?   @map("updated_by") @db.Uuid

  customer         Customer  @relation(fields: [customerId], references: [id])
  assignedToUser   User?     @relation(fields: [assignedToUserId], references: [id])

  @@map("support_tickets")
}

model NotificationQueue {
  id         String    @id @default(uuid()) @db.Uuid
  recipient  String
  channel    String    @map("channel") // EMAIL, SMS, WHATSAPP, WEBHOOK
  eventType  String    @map("event_type")
  subject    String?
  body       String
  status     String    @default("PENDING") // PENDING, SENT, FAILED
  retryCount Int       @default(0) @map("retry_count")
  nextRetryAt DateTime @default(now()) @map("next_retry_at")
  createdAt  DateTime  @default(now()) @map("created_at")
  updatedAt  DateTime  @updatedAt @map("updated_at")
  deletedAt  DateTime? @map("deleted_at")
  createdBy  String?   @map("created_by") @db.Uuid
  updatedBy  String?   @map("updated_by") @db.Uuid

  @@map("notification_queue")
}

model SystemSetting {
  id          String    @id @default(uuid()) @db.Uuid
  key         String    @unique
  value       String
  description String?
  type        String    @default("STRING") // STRING, INTEGER, BOOLEAN, JSON
  createdAt   DateTime  @default(now()) @map("created_at")
  updatedAt   DateTime  @updatedAt @map("updated_at")
  deletedAt   DateTime? @map("deleted_at")
  createdBy   String?   @map("created_by") @db.Uuid
  updatedBy   String?   @map("updated_by") @db.Uuid

  @@map("system_settings")
}
