import type { WorkOrderRow, WorkerUserRow } from '../../repositories/worker-platform/index.js'
import { safeParseJson } from '../admin/admin-query-utils.js'
import {
  normalizeBoolean,
  normalizeInteger,
  normalizePositiveInteger,
} from './worker-normalizers.js'

export function resolveWorkerPermissions(worker: WorkerUserRow) {
  const permission = safeParseJson(worker.level_permission_json)
  const levelDepositFreeAmount = normalizeInteger(permission.depositFreeAmount, 0)
  const personalDepositFreeAmount = Number(worker.personal_deposit_free_amount)
  const hasPersonalDepositFreeAmount =
    worker.personal_deposit_free_amount !== null &&
    worker.personal_deposit_free_amount !== undefined &&
    Number.isInteger(personalDepositFreeAmount) &&
    personalDepositFreeAmount >= 0
  return {
    // 个人额度是在等级额度基础上的追加额度，两者叠加生效。
    depositFreeAmount:
      levelDepositFreeAmount + (hasPersonalDepositFreeAmount ? personalDepositFreeAmount : 0),
    levelDepositFreeAmount,
    personalDepositFreeAmount: hasPersonalDepositFreeAmount ? personalDepositFreeAmount : null,
    maxActiveOrders: normalizePositiveInteger(permission.maxActiveOrders, 1),
    upgradeThreshold: normalizeInteger(permission.upgradeThreshold, 0),
    autoAcceptWithoutEvidence: normalizeBoolean(permission.autoAcceptWithoutEvidence, false),
    visibleDelaySeconds: resolveVisibleDelaySeconds(
      worker.level_key || '',
      permission.visibleDelaySeconds,
    ),
  }
}

/** 整单接单与拼单参与走不同验收路径，拼单配置不能影响整单的 VIP 免审核资格。 */
export function canWorkerAutoAcceptWholeOrder(input: {
  worker: WorkerUserRow
  hasPersonalSharingShare: boolean
}): boolean {
  return (
    !input.hasPersonalSharingShare &&
    resolveWorkerPermissions(input.worker).autoAcceptWithoutEvidence
  )
}

export function resolveVisibleDelaySeconds(levelKey: string, configured?: unknown): number {
  const configuredValue = normalizeInteger(configured, -1)
  if (configuredValue >= 0) return configuredValue
  const defaultDelays: Record<string, number> = {
    vip1: 20,
    vip2: 15,
    vip3: 10,
    vip4: 5,
    vip5: 0,
  }
  return defaultDelays[String(levelKey || '').toLowerCase()] ?? 0
}

export function resolveFreezeDepositAmount(
  workOrder: WorkOrderRow,
  permissions: { depositFreeAmount: number },
) {
  return Math.max(
    0,
    Number(workOrder.required_deposit_amount || 0) - Number(permissions.depositFreeAmount || 0),
  )
}
