import { COMMERCIAL_ACTIONS } from './commercialWorkspaceModel.js'

let idempotencySequence = 0

function toLocalDateTime(value) {
  const date = value instanceof Date ? value : new Date(value)
  const pad = (item) => String(item).padStart(2, '0')
  return [
    date.getFullYear(),
    '-',
    pad(date.getMonth() + 1),
    '-',
    pad(date.getDate()),
    'T',
    pad(date.getHours()),
    ':',
    pad(date.getMinutes())
  ].join('')
}

function nextMonth(value) {
  const date = new Date(value)
  date.setMonth(date.getMonth() + 1)
  return date
}

function createIdempotencyKey(prefix) {
  idempotencySequence += 1
  const random = typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function'
    ? crypto.randomUUID()
    : `${Date.now()}-${idempotencySequence}`
  return `${prefix}-${random}`
}

export function createCommercialForm(kind, account = null, now = new Date()) {
  const current = toLocalDateTime(now)
  const monthEnd = toLocalDateTime(nextMonth(now))
  const plan = account?.plan || {}
  const subscription = account?.subscription || {}
  const firstQuota = account?.quotas?.[0] || {}
  const entitlement = firstQuota.entitlement || {}

  if (kind === 'createPlan') {
    return {
      planCode: String(plan.planCode || ''),
      name: '',
      pricingModel: 'subscription',
      billingInterval: 'annual',
      currency: String(plan.currency || 'CNY'),
      baseFee: '0',
      includedSeats: Number(plan.includedSeats || 1),
      overageEnabled: false,
      effectiveFrom: current,
      effectiveTo: '',
      contractTermsJson: '{}'
    }
  }
  if (kind === 'createSubscription') {
    return {
      subscriptionKey: '',
      planId: String(plan.id || ''),
      status: 'active',
      startsAt: current,
      endsAt: '',
      currentPeriodStart: current,
      currentPeriodEnd: monthEnd,
      seats: Math.max(1, Number(plan.includedSeats || subscription.seats || 1)),
      autoRenew: false,
      externalProvider: '',
      externalSubscriptionId: '',
      metadataJson: '{}'
    }
  }
  if (kind === 'upsertEntitlement') {
    return {
      subscriptionId: String(subscription.id || ''),
      entitlementKey: '',
      metricKey: '',
      entitlementType: 'metered',
      unit: '次',
      includedQuantity: '0',
      hardLimitQuantity: '',
      resetInterval: 'monthly',
      overagePolicy: 'block',
      status: 'active',
      effectiveFrom: current,
      effectiveTo: '',
      configJson: '{}'
    }
  }
  if (kind === 'recordUsage') {
    return {
      subscriptionId: String(subscription.id || ''),
      entitlementId: String(entitlement.id || ''),
      eventType: 'usage',
      quantity: '1',
      occurredAt: current,
      sourceSystem: 'x-financial-web',
      idempotencyKey: createIdempotencyKey('usage'),
      reversalOfEventId: '',
      subjectType: '',
      subjectId: '',
      correlationId: '',
      metadataJson: '{}'
    }
  }
  if (kind === 'recordCost') {
    return {
      subscriptionId: String(subscription.id || ''),
      usageEventId: '',
      eventType: 'incurred',
      costCategory: 'ai_inference',
      quantity: '1',
      unit: '次',
      unitCost: '0',
      originalCurrency: String(subscription.currency || plan.currency || 'CNY'),
      reportingCurrency: String(subscription.currency || plan.currency || 'CNY'),
      fxRate: '1',
      provider: '',
      sku: '',
      modelName: '',
      allocationKey: '',
      occurredAt: current,
      sourceSystem: 'x-financial-web',
      idempotencyKey: createIdempotencyKey('cost'),
      reversalOfCostEventId: '',
      correlationId: '',
      metadataJson: '{}'
    }
  }

  if (kind === 'transitionSubscription') {
    const allowedTargets = resolveSubscriptionTransitionTargets(subscription.status)
    return {
      resourceId: String(subscription.id || ''),
      expectedVersion: Number(subscription.version || 1),
      currentStatus: String(subscription.status || ''),
      targetStatus: allowedTargets[0] || '',
      reason: ''
    }
  }

  const currentResource = kind === 'activatePlan'
    ? plan
    : kind === 'activateSubscription'
      ? subscription
      : entitlement
  return {
    resourceId: String(currentResource.id || ''),
    expectedVersion: Number(currentResource.version || 1),
    reason: ''
  }
}

export function resolveSubscriptionTransitionTargets(status) {
  const allowed = {
    trialing: ['past_due', 'suspended', 'canceled', 'expired'],
    active: ['past_due', 'suspended', 'canceled', 'expired'],
    past_due: ['suspended', 'canceled', 'expired'],
    suspended: ['canceled', 'expired'],
    canceled: [],
    expired: []
  }
  return allowed[String(status || '')] || ['past_due', 'suspended', 'canceled', 'expired']
}

export function commercialActionMeta(kind) {
  return COMMERCIAL_ACTIONS[kind] || null
}

export function buildCommercialConfirmationRows(kind, payload = {}) {
  if (kind === 'createPlan') {
    return [
      `套餐：${payload.name}（${payload.planCode}）`,
      `计价：${payload.pricingModel} / ${payload.billingInterval}`,
      `基础费用：${payload.currency} ${payload.baseFee}`,
      '创建后为草稿，仍需单独激活才会退役同编码旧版本。'
    ]
  }
  if (kind === 'createSubscription') {
    return [
      `订阅键：${payload.subscriptionKey}`,
      `套餐 ID：${payload.planId}`,
      `席位数：${payload.seats}`,
      '订阅快照会固定当时的价格和币种。'
    ]
  }
  if (kind === 'upsertEntitlement') {
    return [
      `权益：${payload.entitlementKey}`,
      `指标：${payload.metricKey}（${payload.unit}）`,
      `超额策略：${payload.overagePolicy}`,
      '已有用量后，影响计费口径的字段不可被覆盖修改。'
    ]
  }
  if (kind.startsWith('activate')) {
    return [
      `资源 ID：${payload.resourceId}`,
      `期望版本：v${payload.expectedVersion}`,
      '若版本已变化，服务器会拒绝本次操作并要求刷新。'
    ]
  }
  if (kind === 'transitionSubscription') {
    return [
      `订阅 ID：${payload.resourceId}`,
      `期望版本：v${payload.expectedVersion}`,
      `目标状态：${payload.targetStatus}`,
      `变更原因：${payload.reason}`,
      '暂停、取消或过期会使商业能力失败关闭；恢复需单独执行重新激活。'
    ]
  }
  if (kind === 'recordUsage') {
    return [
      `权益 ID：${payload.entitlementId}`,
      `事件：${payload.eventType} ${payload.quantity}`,
      `幂等键：${payload.idempotencyKey}`,
      '用量事件写入后不可编辑；纠错必须新增 credit、adjustment 或 reversal。'
    ]
  }
  return [
    `成本：${payload.costCategory} · ${payload.quantity} ${payload.unit}`,
    `原币：${payload.originalCurrency}，报告币：${payload.reportingCurrency}，汇率：${payload.fxRate}`,
    `幂等键：${payload.idempotencyKey}`,
    '成本事件写入后不可编辑；不同币种不会在界面中隐式合并。'
  ]
}
