export interface Order {
  id: string
  userId: string
  amount: number
  currency: string
  status: "pending" | "paid" | "failed" | "refunded"
  items: { type: "book" | "section"; id: string; title: string; price: number }[]
  gateway?: string
  transactionId?: string
  createdAt: string
  updatedAt: string
}

export interface PaymentConfig {
  wechat: {
    enabled: boolean
    qrcode: string
    appId?: string
  }
  alipay: {
    enabled: boolean
    qrcode: string
    appId?: string
  }
  usdt: {
    enabled: boolean
    walletAddress: string
    network: string
  }
}

const ORDERS_KEY = "soul_orders"
const PAYMENT_CONFIG_KEY = "soul_payment_config"

// 订单管理
export function getOrders(): Order[] {
  if (typeof window === "undefined") return []
  const data = localStorage.getItem(ORDERS_KEY)
  return data ? JSON.parse(data) : []
}

export function getOrderById(id: string): Order | undefined {
  return getOrders().find((o) => o.id === id)
}

export function getOrdersByUser(userId: string): Order[] {
  return getOrders().filter((o) => o.userId === userId)
}

export function createOrder(order: Omit<Order, "id" | "createdAt" | "updatedAt">): Order {
  const orders = getOrders()
  const newOrder: Order = {
    ...order,
    id: `order_${Date.now()}_${Math.random().toString(36).slice(2, 9)}`,
    createdAt: new Date().toISOString(),
    updatedAt: new Date().toISOString(),
  }
  orders.push(newOrder)
  localStorage.setItem(ORDERS_KEY, JSON.stringify(orders))
  return newOrder
}

export function updateOrder(id: string, updates: Partial<Order>): Order | null {
  const orders = getOrders()
  const index = orders.findIndex((o) => o.id === id)
  if (index === -1) return null

  orders[index] = {
    ...orders[index],
    ...updates,
    updatedAt: new Date().toISOString(),
  }
  localStorage.setItem(ORDERS_KEY, JSON.stringify(orders))
  return orders[index]
}

// 支付配置管理
export function getPaymentConfig(): PaymentConfig {
  if (typeof window === "undefined") {
    return {
      wechat: { enabled: false, qrcode: "" },
      alipay: { enabled: false, qrcode: "" },
      usdt: { enabled: false, walletAddress: "", network: "TRC20" },
    }
  }
  const data = localStorage.getItem(PAYMENT_CONFIG_KEY)
  return data
    ? JSON.parse(data)
    : {
        wechat: { enabled: true, qrcode: "" },
        alipay: { enabled: true, qrcode: "" },
        usdt: { enabled: false, walletAddress: "", network: "TRC20" },
      }
}

export function updatePaymentConfig(config: Partial<PaymentConfig>): PaymentConfig {
  const current = getPaymentConfig()
  const updated = { ...current, ...config }
  localStorage.setItem(PAYMENT_CONFIG_KEY, JSON.stringify(updated))
  return updated
}

// 模拟支付流程（实际生产环境需要对接真实支付网关）
export async function simulatePayment(orderId: string, gateway: string): Promise<boolean> {
  // 模拟支付延迟
  await new Promise((resolve) => setTimeout(resolve, 1500))

  const order = updateOrder(orderId, {
    status: "paid",
    gateway,
    transactionId: `txn_${Date.now()}`,
  })

  return !!order
}
