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

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

// =============================================================================
// 管理员模块
// =============================================================================

model AdminUser {
  id          String   @id @default(uuid())
  username    String   @unique
  password    String   // bcrypt hashed
  name        String
  role        String   // SUPER_ADMIN, ADMIN, OPERATOR
  status      String   @default("ACTIVE") // ACTIVE, DISABLED
  lastLoginAt DateTime?
  createdAt   DateTime @default(now())
  updatedAt   DateTime @updatedAt

  auditLogs   AuditLog[]

  @@map("admin_users")
}

// =============================================================================
// 系统配置
// =============================================================================

model SystemConfig {
  id          String   @id @default(uuid())
  category    String   // MINING, TRADING, CONTRIBUTION, SYSTEM
  key         String
  value       String
  description String?
  isPublic    Boolean  @default(false)
  createdAt   DateTime @default(now())
  updatedAt   DateTime @updatedAt

  @@unique([category, key])
  @@map("system_configs")
}

// =============================================================================
// 系统账户（运营/省/市）
// =============================================================================

model SystemAccount {
  id                String   @id @default(uuid())
  accountType       String   @unique // OPERATION, PROVINCE, CITY, HEADQUARTERS
  name              String
  description       String?
  totalContribution Decimal  @db.Decimal(30, 8) @default(0)
  createdAt         DateTime @default(now())
  updatedAt         DateTime @updatedAt

  @@map("system_accounts")
}

// =============================================================================
// 初始化记录
// =============================================================================

model InitializationRecord {
  id            String   @id @default(uuid())
  type          String   // MINING_CONFIG, BLACK_HOLE, SYSTEM_ACCOUNTS, ACTIVATE_MINING
  status        String   // PENDING, COMPLETED, FAILED
  config        Json
  executedBy    String
  executedAt    DateTime?
  errorMessage  String?
  createdAt     DateTime @default(now())

  @@map("initialization_records")
}

// =============================================================================
// 审计日志
// =============================================================================

model AuditLog {
  id          String   @id @default(uuid())
  adminId     String
  action      String   // CREATE, UPDATE, DELETE, LOGIN, LOGOUT, INIT
  resource    String   // CONFIG, USER, SYSTEM_ACCOUNT, MINING
  resourceId  String?
  oldValue    Json?
  newValue    Json?
  ipAddress   String?
  userAgent   String?
  createdAt   DateTime @default(now())

  admin       AdminUser @relation(fields: [adminId], references: [id])

  @@index([adminId])
  @@index([action])
  @@index([resource])
  @@index([createdAt(sort: Desc)])
  @@map("audit_logs")
}

// =============================================================================
// 报表快照
// =============================================================================

model DailyReport {
  id                    String   @id @default(uuid())
  reportDate            DateTime @unique @db.Date

  // 用户统计
  totalUsers            Int      @default(0)
  newUsers              Int      @default(0)
  activeUsers           Int      @default(0)

  // 认种统计
  totalAdoptions        Int      @default(0)
  newAdoptions          Int      @default(0)
  totalTrees            Int      @default(0)

  // 算力统计
  totalContribution     Decimal  @db.Decimal(30, 8) @default(0)
  contributionGrowth    Decimal  @db.Decimal(30, 8) @default(0)

  // 挖矿统计
  totalDistributed      Decimal  @db.Decimal(30, 8) @default(0)
  totalBurned           Decimal  @db.Decimal(30, 8) @default(0)

  // 交易统计
  tradingVolume         Decimal  @db.Decimal(30, 8) @default(0)
  tradingAmount         Decimal  @db.Decimal(30, 8) @default(0)
  tradeCount            Int      @default(0)

  // 价格
  openPrice             Decimal  @db.Decimal(30, 18) @default(1)
  closePrice            Decimal  @db.Decimal(30, 18) @default(1)
  highPrice             Decimal  @db.Decimal(30, 18) @default(1)
  lowPrice              Decimal  @db.Decimal(30, 18) @default(1)

  createdAt             DateTime @default(now())

  @@map("daily_reports")
}

// =============================================================================
// CDC 同步表 - 用户数据 (from auth-service)
// =============================================================================

model SyncedUser {
  id                String   @id @default(uuid())
  originalUserId    String   @unique  // auth-service 中的原始 ID
  accountSequence   String   @unique  // 账户序列号
  phone             String
  status            String   // ACTIVE, DISABLED, DELETED
  kycStatus         String   // PENDING, SUBMITTED, VERIFIED, REJECTED
  realName          String?
  isLegacyUser      Boolean  @default(false)  // 是否为 1.0 迁移用户
  createdAt         DateTime
  syncedAt          DateTime @default(now())
  updatedAt         DateTime @updatedAt

  // 关联同步表
  contributionAccount SyncedContributionAccount?
  miningAccount       SyncedMiningAccount?
  tradingAccount      SyncedTradingAccount?

  @@index([phone])
  @@index([status])
  @@index([kycStatus])
  @@index([createdAt(sort: Desc)])
  @@map("synced_users")
}

// =============================================================================
// CDC 同步表 - 算力账户 (from contribution-service)
// =============================================================================

model SyncedContributionAccount {
  id                      String   @id @default(uuid())
  accountSequence         String   @unique
  personalContribution    Decimal  @db.Decimal(30, 8) @default(0)
  teamLevelContribution   Decimal  @db.Decimal(30, 8) @default(0)
  teamBonusContribution   Decimal  @db.Decimal(30, 8) @default(0)
  totalContribution       Decimal  @db.Decimal(30, 8) @default(0)
  effectiveContribution   Decimal  @db.Decimal(30, 8) @default(0)
  hasAdopted              Boolean  @default(false)
  directReferralCount     Int      @default(0)
  unlockedLevelDepth      Int      @default(0)
  syncedAt                DateTime @default(now())
  updatedAt               DateTime @updatedAt

  user                    SyncedUser @relation(fields: [accountSequence], references: [accountSequence])

  @@map("synced_contribution_accounts")
}

// =============================================================================
// CDC 同步表 - 挖矿账户 (from mining-service)
// =============================================================================

model SyncedMiningAccount {
  id                String   @id @default(uuid())
  accountSequence   String   @unique
  totalMined        Decimal  @db.Decimal(30, 8) @default(0)
  availableBalance  Decimal  @db.Decimal(30, 8) @default(0)
  frozenBalance     Decimal  @db.Decimal(30, 8) @default(0)
  totalContribution Decimal  @db.Decimal(30, 8) @default(0)
  syncedAt          DateTime @default(now())
  updatedAt         DateTime @updatedAt

  user              SyncedUser @relation(fields: [accountSequence], references: [accountSequence])

  @@map("synced_mining_accounts")
}

// =============================================================================
// CDC 同步表 - 交易账户 (from trading-service)
// =============================================================================

model SyncedTradingAccount {
  id              String   @id @default(uuid())
  accountSequence String   @unique
  shareBalance    Decimal  @db.Decimal(30, 8) @default(0)
  cashBalance     Decimal  @db.Decimal(30, 8) @default(0)
  frozenShares    Decimal  @db.Decimal(30, 8) @default(0)
  frozenCash      Decimal  @db.Decimal(30, 8) @default(0)
  totalBought     Decimal  @db.Decimal(30, 8) @default(0)
  totalSold       Decimal  @db.Decimal(30, 8) @default(0)
  syncedAt        DateTime @default(now())
  updatedAt       DateTime @updatedAt

  user            SyncedUser @relation(fields: [accountSequence], references: [accountSequence])

  @@map("synced_trading_accounts")
}

// =============================================================================
// CDC 同步表 - 挖矿配置 (from mining-service)
// =============================================================================

model SyncedMiningConfig {
  id                    String   @id @default(uuid())
  totalShares           Decimal  @db.Decimal(30, 8)
  distributionPool      Decimal  @db.Decimal(30, 8)
  remainingDistribution Decimal  @db.Decimal(30, 8)
  halvingPeriodYears    Int
  currentEra            Int      @default(1)
  minuteDistribution    Decimal  @db.Decimal(30, 8)
  isActive              Boolean  @default(false)
  activatedAt           DateTime?
  syncedAt              DateTime @default(now())
  updatedAt             DateTime @updatedAt

  @@map("synced_mining_configs")
}

// =============================================================================
// CDC 同步表 - 每日挖矿统计 (from mining-service)
// =============================================================================

model SyncedDailyMiningStat {
  id                  String   @id @default(uuid())
  statDate            DateTime @unique @db.Date
  totalContribution   Decimal  @db.Decimal(30, 8) @default(0)
  totalDistributed    Decimal  @db.Decimal(30, 8) @default(0)
  totalBurned         Decimal  @db.Decimal(30, 8) @default(0)
  participantCount    Int      @default(0)
  avgContributionRate Decimal  @db.Decimal(30, 18) @default(0)
  syncedAt            DateTime @default(now())
  updatedAt           DateTime @updatedAt

  @@map("synced_daily_mining_stats")
}

// =============================================================================
// CDC 同步表 - 日K线 (from trading-service)
// =============================================================================

model SyncedDayKLine {
  id         String   @id @default(uuid())
  klineDate  DateTime @unique @db.Date
  open       Decimal  @db.Decimal(30, 18)
  high       Decimal  @db.Decimal(30, 18)
  low        Decimal  @db.Decimal(30, 18)
  close      Decimal  @db.Decimal(30, 18)
  volume     Decimal  @db.Decimal(30, 8) @default(0)
  amount     Decimal  @db.Decimal(30, 8) @default(0)
  tradeCount Int      @default(0)
  syncedAt   DateTime @default(now())
  updatedAt  DateTime @updatedAt

  @@map("synced_day_klines")
}

// =============================================================================
// CDC 同步表 - 流通池 (from trading-service)
// =============================================================================

model SyncedCirculationPool {
  id          String   @id @default(uuid())
  totalShares Decimal  @db.Decimal(30, 8) @default(0)
  totalCash   Decimal  @db.Decimal(30, 8) @default(0)
  syncedAt    DateTime @default(now())
  updatedAt   DateTime @updatedAt

  @@map("synced_circulation_pools")
}

// =============================================================================
// CDC 同步表 - 系统账户算力 (from contribution-service)
// =============================================================================

model SyncedSystemContribution {
  id                      String   @id @default(uuid())
  accountType             String   @unique  // OPERATION, PROVINCE, CITY, HEADQUARTERS
  name                    String
  contributionBalance     Decimal  @db.Decimal(30, 8) @default(0)
  contributionNeverExpires Boolean @default(false)
  syncedAt                DateTime @default(now())
  updatedAt               DateTime @updatedAt

  @@map("synced_system_contributions")
}

// =============================================================================
// CDC 同步进度跟踪
// =============================================================================

model CdcSyncProgress {
  id              String   @id @default(uuid())
  sourceTopic     String   @unique
  sourceService   String   // auth, contribution, mining, trading
  lastOffset      String?  // Kafka offset
  lastSequenceNum BigInt   @default(0)
  lastSyncedAt    DateTime @default(now())
  errorCount      Int      @default(0)
  lastError       String?
  updatedAt       DateTime @updatedAt

  @@index([sourceService])
  @@map("cdc_sync_progress")
}

// =============================================================================
// 已处理事件（幂等性）
// =============================================================================

model ProcessedEvent {
  id            String   @id @default(uuid())
  eventId       String   @unique
  eventType     String
  sourceService String
  processedAt   DateTime @default(now())

  @@index([sourceService])
  @@index([processedAt])
  @@map("processed_events")
}

// =============================================================================
// CDC 同步表 - 区域数据 (from mining-wallet-service)
// =============================================================================

model SyncedProvince {
  id        String   @id @default(uuid())
  originalId String  @unique @map("original_id")
  code      String   @unique
  name      String
  status    String   @default("ACTIVE")
  syncedAt  DateTime @default(now())
  updatedAt DateTime @updatedAt

  cities    SyncedCity[]

  @@index([code])
  @@map("synced_provinces")
}

model SyncedCity {
  id          String   @id @default(uuid())
  originalId  String   @unique @map("original_id")
  provinceId  String   @map("province_id")
  code        String   @unique
  name        String
  status      String   @default("ACTIVE")
  syncedAt    DateTime @default(now())
  updatedAt   DateTime @updatedAt

  province    SyncedProvince @relation(fields: [provinceId], references: [originalId])
  userMappings SyncedUserRegionMapping[]

  @@index([provinceId])
  @@index([code])
  @@map("synced_cities")
}

model SyncedUserRegionMapping {
  id              String   @id @default(uuid())
  accountSequence String   @unique @map("account_sequence")
  cityId          String   @map("city_id")
  assignedAt      DateTime @map("assigned_at")
  assignedBy      String?  @map("assigned_by")
  syncedAt        DateTime @default(now())
  updatedAt       DateTime @updatedAt

  city            SyncedCity @relation(fields: [cityId], references: [originalId])

  @@index([cityId])
  @@map("synced_user_region_mappings")
}

// =============================================================================
// CDC 同步表 - 钱包系统账户 (from mining-wallet-service)
// =============================================================================

model SyncedWalletSystemAccount {
  id                String   @id @default(uuid())
  originalId        String   @unique @map("original_id")
  accountType       String   @map("account_type") // HEADQUARTERS, OPERATION, PROVINCE, CITY, FEE, HOT_WALLET, COLD_WALLET
  name              String
  code              String   @unique

  // 关联区域
  provinceId        String?  @map("province_id")
  cityId            String?  @map("city_id")

  // 余额信息
  shareBalance      Decimal  @default(0) @map("share_balance") @db.Decimal(30, 8)
  usdtBalance       Decimal  @default(0) @map("usdt_balance") @db.Decimal(30, 8)
  greenPointBalance Decimal  @default(0) @map("green_point_balance") @db.Decimal(30, 8)
  frozenShare       Decimal  @default(0) @map("frozen_share") @db.Decimal(30, 8)
  frozenUsdt        Decimal  @default(0) @map("frozen_usdt") @db.Decimal(30, 8)

  // 累计统计
  totalInflow       Decimal  @default(0) @map("total_inflow") @db.Decimal(30, 8)
  totalOutflow      Decimal  @default(0) @map("total_outflow") @db.Decimal(30, 8)

  // 链上地址
  blockchainAddress String?  @map("blockchain_address")

  isActive          Boolean  @default(true) @map("is_active")
  syncedAt          DateTime @default(now())
  updatedAt         DateTime @updatedAt

  @@index([accountType])
  @@index([provinceId])
  @@index([cityId])
  @@map("synced_wallet_system_accounts")
}

// =============================================================================
// CDC 同步表 - 池账户 (from mining-wallet-service)
// =============================================================================

model SyncedWalletPoolAccount {
  id            String   @id @default(uuid())
  originalId    String   @unique @map("original_id")
  poolType      String   @unique @map("pool_type") // SHARE_POOL, BLACK_HOLE_POOL, CIRCULATION_POOL
  name          String

  // 余额信息
  balance       Decimal  @default(0) @db.Decimal(30, 8)
  totalInflow   Decimal  @default(0) @map("total_inflow") @db.Decimal(30, 8)
  totalOutflow  Decimal  @default(0) @map("total_outflow") @db.Decimal(30, 8)

  // 黑洞池特有字段
  targetBurn    Decimal? @map("target_burn") @db.Decimal(30, 8)
  remainingBurn Decimal? @map("remaining_burn") @db.Decimal(30, 8)

  isActive      Boolean  @default(true) @map("is_active")
  syncedAt      DateTime @default(now())
  updatedAt     DateTime @updatedAt

  @@index([poolType])
  @@map("synced_wallet_pool_accounts")
}

// =============================================================================
// CDC 同步表 - 用户钱包 (from mining-wallet-service)
// =============================================================================

model SyncedUserWallet {
  id              String   @id @default(uuid())
  originalId      String   @unique @map("original_id")
  accountSequence String   @map("account_sequence")
  walletType      String   @map("wallet_type") // CONTRIBUTION, TOKEN_STORAGE, GREEN_POINTS

  // 余额信息
  balance         Decimal  @default(0) @db.Decimal(30, 8)
  frozenBalance   Decimal  @default(0) @map("frozen_balance") @db.Decimal(30, 8)

  // 累计统计
  totalInflow     Decimal  @default(0) @map("total_inflow") @db.Decimal(30, 8)
  totalOutflow    Decimal  @default(0) @map("total_outflow") @db.Decimal(30, 8)

  isActive        Boolean  @default(true) @map("is_active")
  syncedAt        DateTime @default(now())
  updatedAt       DateTime @updatedAt

  @@unique([accountSequence, walletType])
  @@index([accountSequence])
  @@index([walletType])
  @@map("synced_user_wallets")
}

// =============================================================================
// CDC 同步表 - 提现请求 (from mining-wallet-service)
// =============================================================================

model SyncedWithdrawRequest {
  id              String    @id @default(uuid())
  originalId      String    @unique @map("original_id")
  requestNo       String    @unique @map("request_no")
  accountSequence String    @map("account_sequence")

  // 提现信息
  assetType       String    @map("asset_type")
  amount          Decimal   @db.Decimal(30, 8)
  fee             Decimal   @default(0) @db.Decimal(30, 8)
  netAmount       Decimal   @map("net_amount") @db.Decimal(30, 8)

  // 目标地址
  toAddress       String    @map("to_address")

  // 状态
  status          String    // PENDING, PROCESSING, CONFIRMING, COMPLETED, FAILED, CANCELLED

  // 链上信息
  txHash          String?   @map("tx_hash")
  blockNumber     BigInt?   @map("block_number")
  confirmations   Int       @default(0)

  // 错误信息
  errorMessage    String?   @map("error_message")

  // 审核信息
  approvedBy      String?   @map("approved_by")
  approvedAt      DateTime? @map("approved_at")

  createdAt       DateTime  @map("created_at")
  completedAt     DateTime? @map("completed_at")
  syncedAt        DateTime  @default(now())
  updatedAt       DateTime  @updatedAt

  @@index([accountSequence])
  @@index([status])
  @@index([txHash])
  @@index([createdAt(sort: Desc)])
  @@map("synced_withdraw_requests")
}

// =============================================================================
// CDC 同步表 - 充值记录 (from mining-wallet-service)
// =============================================================================

model SyncedDepositRecord {
  id                String    @id @default(uuid())
  originalId        String    @unique @map("original_id")
  txHash            String    @unique @map("tx_hash")

  // 来源信息
  fromAddress       String    @map("from_address")
  toAddress         String    @map("to_address")

  // 充值信息
  assetType         String    @map("asset_type")
  amount            Decimal   @db.Decimal(30, 8)

  // 链上信息
  blockNumber       BigInt    @map("block_number")
  confirmations     Int       @default(0)

  // 匹配的用户
  matchedAccountSeq String?   @map("matched_account_seq")
  isProcessed       Boolean   @default(false) @map("is_processed")
  processedAt       DateTime? @map("processed_at")

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

  @@index([fromAddress])
  @@index([toAddress])
  @@index([matchedAccountSeq])
  @@index([isProcessed])
  @@map("synced_deposit_records")
}

// =============================================================================
// CDC 同步表 - DEX Swap 记录 (from mining-wallet-service)
// =============================================================================

model SyncedDexSwapRecord {
  id              String    @id @default(uuid())
  originalId      String    @unique @map("original_id")
  swapNo          String    @unique @map("swap_no")
  accountSequence String    @map("account_sequence")

  // Swap 信息
  fromAsset       String    @map("from_asset")
  toAsset         String    @map("to_asset")
  fromAmount      Decimal   @map("from_amount") @db.Decimal(30, 8)
  toAmount        Decimal   @map("to_amount") @db.Decimal(30, 8)
  exchangeRate    Decimal   @map("exchange_rate") @db.Decimal(30, 18)

  // 滑点/手续费
  slippage        Decimal   @default(0) @db.Decimal(10, 4)
  fee             Decimal   @default(0) @db.Decimal(30, 8)

  // 状态
  status          String    // PENDING, PROCESSING, CONFIRMING, COMPLETED, FAILED, CANCELLED

  // 链上信息
  txHash          String?   @map("tx_hash")
  blockNumber     BigInt?   @map("block_number")

  errorMessage    String?   @map("error_message")

  createdAt       DateTime  @map("created_at")
  completedAt     DateTime? @map("completed_at")
  syncedAt        DateTime  @default(now())
  updatedAt       DateTime  @updatedAt

  @@index([accountSequence])
  @@index([status])
  @@index([txHash])
  @@map("synced_dex_swap_records")
}

// =============================================================================
// CDC 同步表 - 区块链地址绑定 (from mining-wallet-service)
// =============================================================================

model SyncedBlockchainAddressBinding {
  id                String    @id @default(uuid())
  originalId        String    @unique @map("original_id")
  accountSequence   String    @unique @map("account_sequence")

  // KAVA 地址
  kavaAddress       String    @unique @map("kava_address")

  // 验证信息
  isVerified        Boolean   @default(false) @map("is_verified")
  verifiedAt        DateTime? @map("verified_at")
  verificationTxHash String?  @map("verification_tx_hash")

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

  @@index([kavaAddress])
  @@map("synced_blockchain_address_bindings")
}

// =============================================================================
// CDC 同步表 - 黑洞合约 (from mining-wallet-service)
// =============================================================================

model SyncedBlackHoleContract {
  id              String   @id @default(uuid())
  originalId      String   @unique @map("original_id")
  contractAddress String   @unique @map("contract_address")
  name            String

  // 累计销毁
  totalBurned     Decimal  @default(0) @map("total_burned") @db.Decimal(30, 8)
  targetBurn      Decimal  @map("target_burn") @db.Decimal(30, 8)
  remainingBurn   Decimal  @map("remaining_burn") @db.Decimal(30, 8)

  isActive        Boolean  @default(true) @map("is_active")
  syncedAt        DateTime @default(now())
  updatedAt       DateTime @updatedAt

  @@map("synced_black_hole_contracts")
}

// =============================================================================
// CDC 同步表 - 销毁到黑洞记录 (from mining-wallet-service)
// =============================================================================

model SyncedBurnToBlackHoleRecord {
  id              String   @id @default(uuid())
  originalId      String   @unique @map("original_id")
  blackHoleId     String   @map("black_hole_id")

  // 销毁信息
  amount          Decimal  @db.Decimal(30, 8)

  // 来源
  sourceType      String   @map("source_type") // USER, SYSTEM_ACCOUNT, POOL, BLOCKCHAIN, EXTERNAL
  sourceAccountSeq String? @map("source_account_seq")
  sourceUserId    String?  @map("source_user_id")
  sourcePoolType  String?  @map("source_pool_type")

  // 链上信息
  txHash          String?  @map("tx_hash")
  blockNumber     BigInt?  @map("block_number")

  // 备注
  memo            String?  @db.Text

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

  @@index([blackHoleId])
  @@index([sourceAccountSeq])
  @@index([txHash])
  @@index([createdAt(sort: Desc)])
  @@map("synced_burn_to_black_hole_records")
}

// =============================================================================
// CDC 同步表 - 手续费配置 (from mining-wallet-service)
// =============================================================================

model SyncedFeeConfig {
  id              String   @id @default(uuid())
  originalId      String   @unique @map("original_id")
  feeType         String   @unique @map("fee_type") // WITHDRAW, TRADE, SWAP, TRANSFER

  // 费率配置
  feeRate         Decimal  @map("fee_rate") @db.Decimal(10, 6)
  minFee          Decimal  @map("min_fee") @db.Decimal(30, 8)
  maxFee          Decimal? @map("max_fee") @db.Decimal(30, 8)

  // 分配比例
  headquartersRate Decimal @map("headquarters_rate") @db.Decimal(10, 6)
  operationRate   Decimal  @map("operation_rate") @db.Decimal(10, 6)
  provinceRate    Decimal  @map("province_rate") @db.Decimal(10, 6)
  cityRate        Decimal  @map("city_rate") @db.Decimal(10, 6)

  isActive        Boolean  @default(true) @map("is_active")
  syncedAt        DateTime @default(now())
  updatedAt       DateTime @updatedAt

  @@map("synced_fee_configs")
}
