import { prisma } from '@/lib/prisma'
import { Prisma } from '@prisma/client'

export interface CreditTransaction {
  id: string
  userId: string
  amount: number
  balance: number
  type: string
  category?: string | null
  note?: string | null
  referenceId?: string | null
  referenceType?: string | null
  expiresAt?: Date | null
  isActive: boolean
  createdAt: Date
  updatedAt: Date
}

export interface CreateCreditTransactionOptions {
  userId: string
  amount: number
  type: 'system_gift' | 'subscription_monthly' | 'user_purchase' | 'consumption' | 'subscription_payment' | 'subscription_refund'
  category?: string
  note?: string
  referenceId?: string
  referenceType?: string
  expiresAt?: Date
}

/**
 * 获取用户当前余额
 */
export async function getUserBalance(userId: string): Promise<number> {
  const latestCredit = await prisma.credit.findFirst({
    where: { userId },
    orderBy: { createdAt: 'desc' },
    select: { balance: true }
  })

  return latestCredit?.balance ?? 0
}

/**
 * 创建信用交易记录并更新余额
 */
export async function createCreditTransaction(
  options: CreateCreditTransactionOptions
): Promise<CreditTransaction> {
  const { userId, amount, type, category, note, referenceId, referenceType, expiresAt } = options

  // 获取当前余额
  const currentBalance = await getUserBalance(userId)
  
  // 计算新余额
  const newBalance = currentBalance + amount

  // 检查余额是否足够（对于消费类型）
  if (type === 'consumption' && newBalance < 0) {
    throw new Error('Insufficient credit balance')
  }

  // 创建交易记录
  const credit = await prisma.credit.create({
    data: {
      userId,
      amount,
      balance: newBalance,
      type,
      category,
      note,
      referenceId,
      referenceType,
      expiresAt,
      isActive: true
    }
  })

  return credit
}

/**
 * 充值信用
 */
export async function addCredit(
  userId: string,
  amount: number,
  type: 'system_gift' | 'subscription_monthly' | 'user_purchase' | 'subscription_refund',
  note?: string,
  expiresAt?: Date
): Promise<CreditTransaction> {
  if (amount <= 0) {
    throw new Error('Amount must be positive')
  }

  return createCreditTransaction({
    userId,
    amount,
    type,
    note,
    expiresAt
  })
}

/**
 * 消费信用
 */
export async function consumeCredit(
  userId: string,
  amount: number,
  category: string,
  referenceId?: string,
  referenceType?: string,
  note?: string
): Promise<CreditTransaction> {
  if (amount <= 0) {
    throw new Error('Amount must be positive')
  }

  return createCreditTransaction({
    userId,
    amount: -amount, // 负数表示消费
    type: 'consumption',
    category,
    referenceId,
    referenceType,
    note
  })
}

/**
 * 获取用户信用交易记录（带分页和筛选）
 */
export interface GetCreditTransactionsOptions {
  userId: string
  page?: number
  limit?: number
  type?: string
  category?: string
  sortBy?: 'createdAt' | 'amount' | 'balance'
  sortOrder?: 'asc' | 'desc'
  startDate?: Date
  endDate?: Date
}

export interface CreditTransactionsResult {
  transactions: CreditTransaction[]
  total: number
  currentBalance: number
}

export async function getCreditTransactions(
  options: GetCreditTransactionsOptions
): Promise<CreditTransactionsResult> {
  const {
    userId,
    page = 1,
    limit = 20,
    type,
    category,
    sortBy = 'createdAt',
    sortOrder = 'desc',
    startDate,
    endDate
  } = options

  const offset = (page - 1) * limit

  // 构建筛选条件
  const where: Prisma.CreditWhereInput = {
    userId,
    isActive: true
  }

  if (type) {
    where.type = type
  }

  if (category) {
    where.category = category
  }

  if (startDate || endDate) {
    where.createdAt = {}
    if (startDate) {
      where.createdAt.gte = startDate
    }
    if (endDate) {
      where.createdAt.lte = endDate
    }
  }

  // 执行查询
  const [transactions, total] = await Promise.all([
    prisma.credit.findMany({
      where,
      orderBy: { [sortBy]: sortOrder },
      skip: offset,
      take: limit
    }),
    prisma.credit.count({ where })
  ])

  // 获取当前余额
  const currentBalance = await getUserBalance(userId)

  return {
    transactions,
    total,
    currentBalance
  }
}

/**
 * 获取用户信用统计信息
 */
export interface CreditStats {
  currentBalance: number
  totalEarned: number
  totalSpent: number
  thisMonthEarned: number
  thisMonthSpent: number
}

export async function getCreditStats(userId: string): Promise<CreditStats> {
  const currentBalance = await getUserBalance(userId)
  
  const now = new Date()
  const startOfMonth = new Date(now.getFullYear(), now.getMonth(), 1)
  
  // 获取总收入和支出
  const totalStats = await prisma.credit.groupBy({
    by: ['type'],
    where: {
      userId,
      isActive: true
    },
    _sum: {
      amount: true
    }
  })

  // 获取本月收入和支出
  const monthlyStats = await prisma.credit.groupBy({
    by: ['type'],
    where: {
      userId,
      isActive: true,
      createdAt: {
        gte: startOfMonth
      }
    },
    _sum: {
      amount: true
    }
  })

  const totalEarned = totalStats
    .filter(stat => stat.type !== 'consumption')
    .reduce((sum, stat) => sum + (stat._sum.amount || 0), 0)

  const totalSpent = Math.abs(totalStats
    .filter(stat => stat.type === 'consumption')
    .reduce((sum, stat) => sum + (stat._sum.amount || 0), 0))

  const thisMonthEarned = monthlyStats
    .filter(stat => stat.type !== 'consumption')
    .reduce((sum, stat) => sum + (stat._sum.amount || 0), 0)

  const thisMonthSpent = Math.abs(monthlyStats
    .filter(stat => stat.type === 'consumption')
    .reduce((sum, stat) => sum + (stat._sum.amount || 0), 0))

  return {
    currentBalance,
    totalEarned,
    totalSpent,
    thisMonthEarned,
    thisMonthSpent
  }
}

/**
 * 模拟器运行时消费信用
 */
export async function consumeCreditForSimulation(
  userId: string,
  cost: number,
  simulatorRunId: string,
  note?: string
): Promise<CreditTransaction> {
  return consumeCredit(
    userId,
    cost,
    'simulation',
    simulatorRunId,
    'simulator_run',
    note || `AI model simulation cost`
  )
}

/**
 * 订阅付费时添加信用（用于记录订阅费用和赠送的信用）
 */
export async function addCreditForSubscription(
  userId: string,
  creditAmount: number,
  subscriptionId: string,
  planName: string,
  note?: string
): Promise<CreditTransaction> {
  return createCreditTransaction({
    userId,
    amount: creditAmount,
    type: 'subscription_monthly',
    category: 'subscription',
    referenceId: subscriptionId,
    referenceType: 'subscription',
    note: note || `${planName} subscription monthly credit`
  })
}

/**
 * 记录订阅费用支出（如果需要记录用户付费）
 */
export async function recordSubscriptionPayment(
  userId: string,
  paymentAmount: number,
  subscriptionId: string,
  planName: string,
  note?: string
): Promise<CreditTransaction> {
  return createCreditTransaction({
    userId,
    amount: -paymentAmount, // 负数表示支出
    type: 'subscription_payment',
    category: 'subscription',
    referenceId: subscriptionId,
    referenceType: 'subscription',
    note: note || `${planName} subscription payment`
  })
}

/**
 * 订阅取消时记录退款（如果有的话）
 */
export async function addCreditForSubscriptionRefund(
  userId: string,
  refundAmount: number,
  subscriptionId: string,
  planName: string,
  note?: string
): Promise<CreditTransaction> {
  return createCreditTransaction({
    userId,
    amount: refundAmount,
    type: 'subscription_refund',
    category: 'subscription',
    referenceId: subscriptionId,
    referenceType: 'subscription',
    note: note || `${planName} subscription refund`
  })
}