export type WorkerLevelRow = {
  id: number
  level_key: string
  name: string
  sort_order: number
  status: string
  permission_json: string | Record<string, unknown>
  created_at: string
  updated_at: string
}

export type WorkerUserRow = {
  id: number
  username: string
  password_hash: string
  display_name: string
  phone: string
  level_id: number | null
  /** 个人追加免押额度（分），与等级额度叠加。 */
  personal_deposit_free_amount?: number | null
  status: string
  worker_type: string
  review_note: string
  frozen_reason: string
  frozen_at: string | null
  session_version: number
  created_at: string
  updated_at: string
  reviewed_at: string | null
  inviter_id: number | null
  invite_code: string
  inviter_username?: string
  inviter_display_name?: string
  level_key?: string
  level_name?: string
  level_permission_json?: string | Record<string, unknown>
  level_penalty_accepted_count?: number
  available_amount?: number
  frozen_deposit_amount?: number
  pending_unfreeze_amount?: number
  total_credited_amount?: number
  total_settled_amount?: number
  rename_cards?: number
  last_renamed_at?: string | null
}

export type WorkerSessionRow = {
  id: number
  session_id: string
  worker_id: number
  device_id: string
  device_type: string
  device_name: string
  user_agent: string
  ip_address: string
  status: string
  issued_at: string
  last_seen_at: string
  expires_at: string
  revoked_at: string | null
  created_at: string
  updated_at: string
}

export type WorkerWalletRow = {
  worker_id: number
  available_amount: number
  frozen_deposit_amount: number
  frozen_withdraw_amount: number
  pending_unfreeze_amount: number
  total_credited_amount: number
  total_settled_amount: number
  created_at: string
  updated_at: string
}

export type WorkerCancelRequestRow = {
  id: number
  work_order_id: number
  work_order_share_id: number | null
  worker_id: number
  reason: string
  status: string
  review_note: string
  reviewed_by: string
  level_before_id: number | null
  created_at: string
  reviewed_at: string | null
  updated_at: string
  platform_order_id?: string
  shop_name?: string
  product_name?: string
  worker_username?: string
  worker_display_name?: string
  share_quantity?: number | null
}

export type WorkerOrderFeedbackRow = {
  id: number
  work_order_id: number
  work_order_share_id: number | null
  worker_id: number
  content: string
  status: string
  reply: string
  handled_by: string
  created_at: string
  handled_at: string | null
  updated_at: string
  work_order_no?: string
  product_name?: string
  shop_name?: string
  worker_username?: string
  worker_display_name?: string
  share_quantity?: number | null
}

export type WorkerDepositUnfreezeRow = {
  id: number
  worker_id: number
  work_order_id: number
  amount: number
  fund_type: 'deposit' | 'reward' | 'legacy_combined' | string
  unfreeze_at: string
  status: string
  released_at: string | null
  created_at: string
  updated_at: string
}

export type WorkerWalletLedgerRow = {
  id: number
  worker_id: number
  ledger_type: string
  amount: number
  balance_after: number
  frozen_after: number
  related_work_order_id: number | null
  audit_status: string
  note: string
  payload_json: string | Record<string, unknown>
  created_at: string
  related_platform_order_id?: string | null
}

export type WorkerAfterSalesCaseRow = {
  id: number
  case_no: string
  work_order_id: number
  work_order_share_id: number | null
  worker_id: number
  problem_type: string
  complaint_note: string
  complaint_files_json: string | Record<string, unknown> | unknown[]
  acceptance_snapshot_json: string | Record<string, unknown>
  status: string
  worker_response: string
  worker_response_files_json: string | Record<string, unknown> | unknown[]
  responded_at: string | null
  resolution_action: string
  resolution_note: string
  recovery_amount: number
  pending_deposit_deduction_amount: number
  available_deduction_amount: number
  debt_amount: number
  refunded_amount?: number
  refunded_at?: string | null
  refunded_by?: string
  created_by: string
  resolved_by: string
  resolved_at: string | null
  created_at: string
  updated_at: string
  work_order_no?: string
  platform_order_id?: string
  product_name?: string
  shop_name?: string
  worker_username?: string
  worker_display_name?: string
  share_quantity?: number | null
}

export type WorkerAfterSalesCaseEventRow = {
  id: number
  case_id: number
  actor_type: string
  actor_id: string
  event_type: string
  payload_json: string | Record<string, unknown>
  created_at: string
}

export type WorkerAfterSalesDebtRow = {
  id: number
  case_id: number
  worker_id: number
  original_amount: number
  outstanding_amount: number
  status: string
  created_at: string
  settled_at: string | null
  updated_at: string
}

export type WorkerFinanceRequestRow = {
  id: number
  worker_id: number
  request_type: string
  status: string
  amount: number
  /** 申请时已冻结的资金额度；0 表示旧数据未冻结（迁移前遗留）。 */
  frozen_amount: number
  account_channel: string
  account_name: string
  account_no: string
  note: string
  reviewed_note: string
  payload_json: string | Record<string, unknown>
  created_at: string
  updated_at: string
  reviewed_at: string | null
  worker_username?: string
  worker_display_name?: string
  worker_phone?: string
  worker_type?: string
  worker_level_key?: string
  worker_level_name?: string
  worker_withdraw_request_count?: number
  worker_total_withdraw_amount?: number
}

export type WorkerWithdrawalAccountRow = {
  worker_id: number
  account_channel: string
  account_name: string
  account_no: string
  alipay_qr_code_json: string | Record<string, unknown>
  wechat_qr_code_json: string | Record<string, unknown>
  created_at: string
}

export type WorkCategoryRow = {
  id: number
  category_key: string
  name: string
  sort_order: number
  status: string
  created_at: string
  updated_at: string
}

export type WorkProductRuleRow = {
  id: number
  rule_key: string
  provider: string
  platform: string
  shop_id: string
  sku_code: string
  product_name: string
  match_type: string
  category_id: number | null
  enabled: boolean
  auto_create: boolean
  reward_amount: number
  unit_price_fen: number
  required_deposit_amount: number
  deposit_threshold_amount: number
  sharing_enabled: boolean
  sharing_total_quantity: number
  sharing_unit_reward: number
  sharing_auto_from_order: boolean
  timeout_minutes: number
  timeout_policy: string
  acceptance_mode: string
  gift_cooldown_hours: number
  gift_cooldown_minutes: number
  requirement_json: string | Record<string, unknown>
  match_json: string | Record<string, unknown>
  sort_order: number
  created_at: string
  updated_at: string
  category_name?: string
}

export type WorkProductRuleMappingRow = {
  id: number
  rule_id: number
  seller_ids_json: string | string[]
  rel_item_id: string
  item_title: string
  rel_sku_id: string
  sku_nick: string
  sku_match_mode: 'fuzzy' | 'exact' | string
  mapping_type: 'product_default' | 'sku_exact' | 'sku_series' | string
  enabled: boolean
  created_at: string
  updated_at: string
  rule_key?: string
  product_name?: string
}

export type WorkProductMatchLogRow = {
  id: number
  order_id: number | null
  order_item_id: number | null
  source: string
  seller_id: string
  rel_item_id: string
  item_title: string
  rel_sku_id: string
  sku_nick: string
  match_status: 'matched' | 'unmatched' | 'ambiguous' | string
  rule_id: number | null
  mapping_id: number | null
  candidates_json: string | Record<string, unknown> | unknown[]
  raw_payload_json: string | Record<string, unknown>
  created_at: string
  rule_key?: string
  product_name?: string
}

export type WorkOrderShareRow = {
  id: number
  work_order_id: number
  worker_id: number
  quantity: number
  unit_reward: number
  share_reward: number
  share_deposit: number
  status: string
  acceptance_json: string | Record<string, unknown>
  draft_acceptance_json: string | Record<string, unknown>
  submitted_at: string | null
  accepted_at: string | null
  created_at: string
  updated_at: string
  worker_username?: string
  worker_display_name?: string
}

export type WorkOrderRow = {
  id: number
  work_order_no: string
  /** 自动建单命中的接单模板；历史或人工工单可能为空。 */
  product_rule_id?: number | null
  order_id: number | null
  order_item_id: number | null
  task_id: number | null
  platform_order_id: string
  product_name: string
  category_id: number | null
  status: string
  reward_amount: number
  required_deposit_amount: number
  deposit_threshold_amount: number
  assigned_worker_id: number | null
  last_assigned_worker_id: number | null
  material_json: string | Record<string, unknown>
  requirement_json: string | Record<string, unknown>
  acceptance_json: string | Record<string, unknown>
  draft_acceptance_json: string | Record<string, unknown>
  admin_note: string
  problem_note: string
  sharing_enabled: boolean
  sharing_total_quantity: number
  sharing_unit_reward: number
  published_at: string | null
  hall_queued_at: string | null
  pinned_at: string | null
  assigned_at: string | null
  submitted_at: string | null
  accepted_at: string | null
  deadline_at: string | null
  timeout_minutes: number
  timeout_policy: string
  /** 验收模式：standard / friend_gift；friend_gift 建单时从接单模板拷贝。 */
  acceptance_mode: string
  /** 好友赠送阶段：material_required / material_submitted / friend_countdown；gift_ready 实时计算。 */
  gift_phase: string
  /** 打手本人资料（昵称/ID/区服/系统 + 主页截图），仅 friend_gift 模式使用。 */
  booster_material_json: string | Record<string, unknown>
  friend_added_at: string | null
  gift_available_at: string | null
  gift_cooldown_hours: number
  gift_cooldown_minutes: number
  created_at: string
  updated_at: string
  /** 拼单聚合字段，由工单查询统一计算。 */
  active_share_quantity?: number
  pending_share_count?: number
  category_name?: string
  worker_username?: string
  worker_display_name?: string
  /** 取消信息，由工单查询从取消类事件推导，仅已取消工单有值。 */
  cancel_reason?: string | null
  cancel_event_type?: string | null
  cancel_actor_type?: string | null
  cancel_actor_id?: string | null
  cancelled_at?: string | null
}

export type ProblemWorkOrderResolutionAction =
  | 'return_to_worker'
  | 'reopen'
  | 'cancel_release'
  | 'cancel_deduct'

export type GrabWorkOrderFailureReason =
  | 'worker_active_order_limit'
  | 'worker_deposit_insufficient'
  | 'work_order_not_open'

export type GrabWorkOrderResult = {
  order: WorkOrderRow | null
  failureReason: GrabWorkOrderFailureReason | null
}

export type ListInput = {
  page?: number
  pageSize?: number
  /** 单状态筛选（兼容 worker 用户等其他列表） */
  status?: string
  /** 支持多个状态同时筛选（空数组表示全部状态） */
  statuses?: string[]
  /** 后台待办跳转时按工单主键精确定位 */
  workOrderId?: number
  keyword?: string
  /** 打手类型筛选：internal 内部打手 / external 外部打手 */
  workerType?: string
  /** 后台打手列表按主键精确定位。 */
  workerId?: number
  /** 后台打手列表按 VIP 等级筛选。 */
  levelId?: number
  /** 后台待验收筛选：普通单按接单人，拼单按参与打手等级。 */
  workerLevelIds?: number[]
  categoryId?: number
  workerSharingId?: number
  /** 大厅候选集合的总展示上限；筛选与分页在候选集合内执行。 */
  hallCandidateLimit?: number
  hallCategoryLimits?: Record<string, number>
  visibleAfterIso?: string
  /** 抢单大厅隐藏已被拼完的工单。 */
  excludeFilledSharing?: boolean
  /** VIP 免审核后仍在补图期限内的订单；与状态筛选取并集 */
  vipEvidencePending?: boolean
  /** 验收模式筛选：standard / friend_gift。 */
  acceptanceMode?: string
  /** 好友赠送阶段筛选：material_required / material_submitted / friend_countdown / gift_ready。 */
  giftPhase?: string
  /** 置顶订单优先展示（抢单大厅使用） */
  pinnedFirst?: boolean
  sort?: 'id_desc' | 'worker_claimed_at_desc'
  /** 后台使用拼单聚合业务状态；大厅和打手列表使用原始生命周期。 */
  useOperationalStatus?: boolean
  /** 创建时间区间（YYYY-MM-DD，上海时区，含起止日）；后台列表筛选使用。 */
  createdFrom?: string
  createdTo?: string
}

export type WorkOrderStatistics = {
  totalCount: number
  userPaymentAmount: number
  rewardAmount: number
  refundAmount: number
  statusCounts: Record<string, number>
}

export type WorkOrderCapabilities = {
  canEdit: boolean
  canConfigureSharing: boolean
  canAssign: boolean
  canPin: boolean
  canUnpublish: boolean
  canUpdateMaterial: boolean
  canAccept: boolean
  canMarkProblem: boolean
  canDelete: boolean
  canReopen: boolean
  canPublish: boolean
  canCancel: boolean
  canCancelSharing: boolean
  canResolveProblem: boolean
  canDeduct: boolean
  canConfirmFriend: boolean
  canCompleteGiftCooldown: boolean
  canResetGiftFlow: boolean
}

export type ProductRuleListInput = {
  page?: number
  pageSize?: number
  enabled?: boolean | null
  keyword?: string
  categoryId?: number
}

export type WalletLedgerListInput = {
  page?: number
  pageSize?: number
  workerId?: number
  ledgerType?: string
}

export type FinanceRequestListInput = {
  page?: number
  pageSize?: number
  /** 后台待办跳转时按资金申请主键精确定位 */
  requestId?: number
  workerId?: number
  status?: string
  requestType?: string
  keyword?: string
  /** 申请时间区间（YYYY-MM-DD 含全天，或 YYYY-MM-DD HH:mm:ss 精确到秒；上海时区）；后台列表筛选使用。 */
  createdFrom?: string
  createdTo?: string
  /** 收款渠道筛选：alipay / wechat */
  accountChannel?: string
}

export type CreateWorkerInput = {
  username: string
  passwordHash: string
  displayName: string
  phone: string
  levelId: number | null
  status: string
  workerType?: string
  inviterId?: number | null
  inviteCode: string
  /** 注册场景下与账号、钱包在同一事务内消费验证码。 */
  smsCodeId?: number
  now: string
}

export type CreateWorkOrderInput = {
  workOrderNo: string
  productRuleId?: number | null
  orderId?: number | null
  orderItemId?: number | null
  taskId?: number | null
  platformOrderId: string
  productName: string
  categoryId?: number | null
  status: string
  rewardAmount: number
  requiredDepositAmount: number
  depositThresholdAmount: number
  sharingEnabled?: boolean
  sharingTotalQuantity?: number
  sharingUnitReward?: number
  timeoutMinutes?: number
  timeoutPolicy?: string
  acceptanceMode?: string
  giftCooldownHours?: number
  giftCooldownMinutes?: number
  materialJson: string
  requirementJson: string
  now: string
}
