// prisma/schema.prisma

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

datasource db {
  provider = "postgresql"
}

// 备份分片存储
model BackupShare {
  shareId           BigInt   @id @default(autoincrement()) @map("share_id")

  // 用户标识 (来自 identity-service)
  userId            BigInt   @unique @map("user_id")
  accountSequence   String   @unique @map("account_sequence") @db.VarChar(12) // 格式: D + YYMMDD + 5位序号

  // MPC 密钥信息
  publicKey         String   @unique @map("public_key") @db.VarChar(130)
  partyIndex        Int      @default(2) @map("party_index")  // Backup = Party 2
  threshold         Int      @default(2)
  totalParties      Int      @default(3) @map("total_parties")

  // 加密的分片数据 (AES-256-GCM 加密)
  encryptedShareData String  @map("encrypted_share_data") @db.Text
  encryptionKeyId    String  @map("encryption_key_id") @db.VarChar(64)  // 密钥轮换支持

  // 状态管理
  status            String   @default("ACTIVE") @db.VarChar(20)  // ACTIVE, REVOKED, ROTATED

  // 访问控制
  accessCount       Int      @default(0) @map("access_count")  // 访问次数限制
  lastAccessedAt    DateTime? @map("last_accessed_at")

  // 时间戳
  createdAt         DateTime @default(now()) @map("created_at")
  updatedAt         DateTime @updatedAt @map("updated_at")
  revokedAt         DateTime? @map("revoked_at")

  // 索引
  @@index([publicKey], name: "idx_backup_public_key")
  @@index([status], name: "idx_backup_status")
  @@index([createdAt], name: "idx_backup_created")
  @@map("backup_shares")
}

// 访问审计日志
model ShareAccessLog {
  logId             BigInt   @id @default(autoincrement()) @map("log_id")

  shareId           BigInt   @map("share_id")
  userId            BigInt   @map("user_id")

  action            String   @db.VarChar(20)  // STORE, RETRIEVE, REVOKE, ROTATE
  sourceService     String   @map("source_service") @db.VarChar(50)  // identity-service, recovery-service
  sourceIp          String   @map("source_ip") @db.VarChar(45)

  success           Boolean  @default(true)
  errorMessage      String?  @map("error_message") @db.Text

  createdAt         DateTime @default(now()) @map("created_at")

  @@index([shareId], name: "idx_log_share")
  @@index([userId], name: "idx_log_user")
  @@index([action], name: "idx_log_action")
  @@index([createdAt], name: "idx_log_created")
  @@map("share_access_logs")
}
