// 订阅计划配置
export const SUBSCRIPTION_PLANS = {
  free: {
    name: 'Free',
    maxVersionLimit: 3,
    promptLimit: 20,
    monthlyCredit: 0, // 免费版没有月度额度
    initialCredit: 5, // 注册时一次性赠送5USD，1个月后过期
    price: 0
  },
  pro: {
    name: 'Pro',
    maxVersionLimit: 10,
    promptLimit: 500,
    monthlyCredit: 20, // 每月20USD额度
    initialCredit: 0, // Pro用户不需要初始额度
    price: 19.9
  }
} as const

export type SubscriptionPlan = keyof typeof SUBSCRIPTION_PLANS

// 获取用户的版本限制
export function getUserVersionLimit(user: {
  versionLimit: number
  subscribePlan: string
  maxVersionLimit: number
}): number {
  const plan = user.subscribePlan as SubscriptionPlan
  const planConfig = SUBSCRIPTION_PLANS[plan]
  
  if (!planConfig) {
    // 如果订阅计划无效，使用免费计划的限制
    return Math.min(user.versionLimit, SUBSCRIPTION_PLANS.free.maxVersionLimit)
  }
  
  // 用户设置的限制不能超过订阅计划的最大限制
  return Math.min(user.versionLimit, planConfig.maxVersionLimit)
}

// 获取用户的最大版本限制（基于订阅）
export function getMaxVersionLimit(subscribePlan: string): number {
  const plan = subscribePlan as SubscriptionPlan
  const planConfig = SUBSCRIPTION_PLANS[plan]
  
  return planConfig?.maxVersionLimit || SUBSCRIPTION_PLANS.free.maxVersionLimit
}

// 检查用户是否可以创建新版本
export function canCreateNewVersion(
  currentVersionCount: number,
  user: {
    versionLimit: number
    subscribePlan: string
    maxVersionLimit: number
  }
): boolean {
  const versionLimit = getUserVersionLimit(user)
  return currentVersionCount < versionLimit
}

// 计算需要删除的版本数量
export function getVersionsToDelete(
  currentVersionCount: number,
  user: {
    versionLimit: number
    subscribePlan: string
    maxVersionLimit: number
  }
): number {
  const versionLimit = getUserVersionLimit(user)
  return Math.max(0, currentVersionCount - versionLimit + 1) // +1 因为要创建新版本
}

// 获取用户的提示词限制
export function getPromptLimit(subscribePlan: string): number {
  const plan = subscribePlan as SubscriptionPlan
  const planConfig = SUBSCRIPTION_PLANS[plan]
  
  return planConfig?.promptLimit || SUBSCRIPTION_PLANS.free.promptLimit
}

// 检查用户是否可以创建新提示词
export async function canCreateNewPrompt(userId: string): Promise<boolean> {
  const { prisma } = await import('@/lib/prisma')
  
  const user = await prisma.user.findUnique({
    where: { id: userId },
    select: { subscribePlan: true }
  })
  
  if (!user) return false
  
  const promptLimit = getPromptLimit(user.subscribePlan)
  const currentPromptCount = await prisma.prompt.count({
    where: { userId }
  })
  
  return currentPromptCount < promptLimit
}