import { prisma } from '@/lib/prisma'
import type { SubscriptionPlan } from '@prisma/client'
import { isPlanPro } from '@/lib/subscription-utils'

// 订阅状态类型
export interface SubscriptionStatus {
  isActive: boolean
  planId: string
  stripeSubscriptionId?: string
  currentPeriodStart?: Date
  currentPeriodEnd?: Date
  cancelAtPeriodEnd?: boolean
  status?: string
}

// 用户权益类型
export interface UserPermissions {
  maxVersionLimit: number
  promptLimit: number
  features: string[]
  canCreatePrompt: boolean
  canCreateVersion: boolean
}

// 套餐配置类型
export interface PlanLimits {
  maxVersionLimit: number
  promptLimit: number
  creditMonthly: number
}

export interface PlanFeatures {
  [key: string]: boolean | string | number
}

export class SubscriptionService {
  /**
   * 判断套餐是否为 Pro 级别（价格超过 19）
   */
  static isPlanPro(plan: SubscriptionPlan | null): boolean {
    return isPlanPro(plan)
  }

  /**
   * 根据套餐 ID 判断是否为 Pro 级别
   */
  static async isPlanIdPro(planId: string): Promise<boolean> {
    const plan = await this.getPlanById(planId)
    return this.isPlanPro(plan)
  }

  /**
   * 判断用户是否为 Pro 用户
   */
  static async isUserPro(userId: string): Promise<boolean> {
    try {
      const subscriptionStatus = await this.getUserSubscriptionStatus(userId)
      return await this.isPlanIdPro(subscriptionStatus.planId)
    } catch (error) {
      console.error('Error checking if user is pro:', error)
      return false
    }
  }
  /**
   * 获取所有可用的订阅套餐
   */
  static async getAvailablePlans(): Promise<SubscriptionPlan[]> {
    return await prisma.subscriptionPlan.findMany({
      where: { isActive: true },
      orderBy: { sortOrder: 'asc' }
    })
  }

  /**
   * 根据ID获取套餐
   */
  static async getPlanById(planId: string): Promise<SubscriptionPlan | null> {
    return await prisma.subscriptionPlan.findUnique({
      where: { id: planId }
    })
  }

  /**
   * 获取 Pro 套餐（名称为 "pro"）
   */
  static async getProPlan(): Promise<SubscriptionPlan | null> {
    return await prisma.subscriptionPlan.findFirst({
      where: {
        name: 'pro',
        isActive: true
      }
    })
  }

  /**
   * 获取 Pro 套餐的 Stripe 价格 ID
   */
  static async getProPriceId(): Promise<string | null> {
    const proPlan = await this.getProPlan()
    return proPlan?.stripePriceId || null
  }

  /**
   * 获取用户的当前订阅状态（从订阅表查询）
   */
  static async getUserSubscriptionStatus(userId: string): Promise<SubscriptionStatus> {
    // 查找用户当前有效的订阅
    const activeSubscription = await this.getUserActiveSubscription(userId)

    if (activeSubscription) {
      return {
        isActive: true,
        planId: activeSubscription.subscriptionPlanId,
        stripeSubscriptionId: activeSubscription.stripeSubscriptionId || undefined,
        currentPeriodStart: activeSubscription.startDate || undefined,
        currentPeriodEnd: activeSubscription.endDate || undefined,
        status: activeSubscription.status
      }
    }

    // 没有有效订阅，返回免费套餐
    return {
      isActive: true,
      planId: 'free'
    }
  }

  /**
   * 获取用户当前有效的订阅记录
   */
  static async getUserActiveSubscription(userId: string) {
    const now = new Date()

    return await prisma.subscription.findFirst({
      where: {
        userId,
        isActive: true,
        status: 'active',
        startDate: { lte: now },
        endDate: { gte: now }
      },
      orderBy: { createdAt: 'desc' }
    })
  }

  /**
   * 创建新的订阅记录（用户点击订阅时）
   */
  static async createPendingSubscription(
    userId: string,
    planId: string,
    stripeSubscriptionId?: string,
    stripeCustomerId?: string
  ) {
    return await prisma.subscription.create({
      data: {
        userId,
        subscriptionPlanId: planId,
        stripeSubscriptionId,
        stripeCustomerId,
        isActive: false,
        status: 'pending'
      }
    })
  }

  /**
   * 激活订阅（Stripe 订阅成功回调时）
   */
  static async activateSubscription(
    stripeSubscriptionId: string,
    startDate: Date,
    endDate: Date,
    metadata?: Record<string, unknown>
  ) {
    return await prisma.subscription.updateMany({
      where: {
        stripeSubscriptionId,
        status: 'pending'
      },
      data: {
        isActive: true,
        status: 'active',
        startDate,
        endDate,
        metadata: metadata ? JSON.parse(JSON.stringify(metadata)) : undefined,
        updatedAt: new Date()
      }
    })
  }

  /**
   * 创建续订记录（Stripe 续订成功时）
   */
  static async createRenewalSubscription(
    userId: string,
    planId: string,
    stripeSubscriptionId: string,
    startDate: Date,
    endDate: Date,
    stripeCustomerId?: string,
    metadata?: Record<string, unknown>
  ) {
    return await prisma.subscription.create({
      data: {
        userId,
        subscriptionPlanId: planId,
        stripeSubscriptionId,
        stripeCustomerId,
        isActive: true,
        status: 'active',
        startDate,
        endDate,
        metadata: metadata ? JSON.parse(JSON.stringify(metadata)) : undefined
      }
    })
  }

  /**
   * 获取用户的权益和限制
   */
  static async getUserPermissions(userId: string): Promise<UserPermissions> {
    const user = await prisma.user.findUnique({
      where: { id: userId },
      include: { subscriptionPlan: true }
    })

    if (!user) {
      throw new Error('User not found')
    }

    // 获取实时订阅状态
    const subscriptionStatus = await this.getUserSubscriptionStatus(userId)

    // 获取对应的套餐配置
    const plan = await this.getPlanById(subscriptionStatus.planId)
    if (!plan) {
      throw new Error('Subscription plan not found')
    }

    const limits = plan.limits as unknown as PlanLimits
    const features = plan.features as unknown as PlanFeatures

    // 用户自定义的版本限制不能超过套餐限制
    const maxVersionLimit = Math.min(user.versionLimit, limits.maxVersionLimit)

    // 检查当前使用情况（完全基于套餐限制，忽略用户表中的 promptLimit）
    const currentPromptCount = await prisma.prompt.count({
      where: { userId }
    })

    return {
      maxVersionLimit,
      promptLimit: limits.promptLimit, // 完全从套餐配置获取
      features: Object.keys(features).filter(key => features[key] === true),
      canCreatePrompt: currentPromptCount < limits.promptLimit, // 使用套餐限制
      canCreateVersion: true // 这个需要在具体创建时检查
    }
  }

  /**
   * 检查用户是否可以创建新的提示词
   */
  static async canCreatePrompt(userId: string): Promise<boolean> {
    const permissions = await this.getUserPermissions(userId)
    return permissions.canCreatePrompt
  }

  /**
   * 检查用户是否可以创建新版本
   */
  static async canCreateVersion(userId: string, promptId: string): Promise<boolean> {
    const permissions = await this.getUserPermissions(userId)
    
    // 获取当前版本数量
    const currentVersionCount = await prisma.promptVersion.count({
      where: { promptId }
    })

    return currentVersionCount < permissions.maxVersionLimit
  }

  /**
   * 计算需要删除的版本数量（当超出限制时）
   */
  static async getVersionsToDelete(userId: string, promptId: string): Promise<number> {
    const permissions = await this.getUserPermissions(userId)
    
    const currentVersionCount = await prisma.promptVersion.count({
      where: { promptId }
    })

    return Math.max(0, currentVersionCount - permissions.maxVersionLimit + 1)
  }

  /**
   * 更新用户的订阅套餐（通常在 webhook 中调用）
   */
  static async updateUserSubscriptionPlan(userId: string, planId: string): Promise<void> {
    await prisma.user.update({
      where: { id: userId },
      data: { subscriptionPlanId: planId }
    })
  }

  /**
   * 根据 Stripe 价格 ID 获取套餐 ID
   */
  static async getPlanIdByStripePriceId(stripePriceId: string): Promise<string> {
    const plan = await prisma.subscriptionPlan.findFirst({
      where: { stripePriceId }
    })
    return plan?.id || 'free'
  }
}
