import { NextRequest, NextResponse } from 'next/server'
import { createServerClient } from '@supabase/ssr'
import { cookies } from 'next/headers'
import { prisma } from '@/lib/prisma'
import { SubscriptionService } from '@/lib/subscription-service'

// 验证管理员权限
async function verifyAdmin() {
  const cookieStore = await cookies()
  const supabase = createServerClient(
    process.env.NEXT_PUBLIC_SUPABASE_URL!,
    process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!,
    {
      cookies: {
        get(name: string) {
          return cookieStore.get(name)?.value
        },
      },
    }
  )

  const { data: { user }, error: authError } = await supabase.auth.getUser()

  if (authError || !user) {
    return null
  }

  const userData = await prisma.user.findUnique({
    where: { id: user.id },
    select: { isAdmin: true }
  })

  return userData?.isAdmin ? user : null
}

// GET - 获取所有订阅套餐
export async function GET() {
  try {
    const user = await verifyAdmin()
    if (!user) {
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
    }

    const plans = await SubscriptionService.getAvailablePlans()
    return NextResponse.json({ plans })
  } catch (error) {
    console.error('Error fetching subscription plans:', error)
    return NextResponse.json(
      { error: 'Failed to fetch subscription plans' },
      { status: 500 }
    )
  }
}

// POST - 创建新的订阅套餐
export async function POST(request: NextRequest) {
  try {
    const user = await verifyAdmin()
    if (!user) {
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
    }

    const {
      id,
      name,
      displayName,
      description,
      price,
      currency = 'usd',
      interval = 'month',
      stripePriceId,
      isActive = true,
      sortOrder = 0,
      features,
      limits
    } = await request.json()

    // 验证必填字段
    if (!id || !name || !displayName || !features || !limits) {
      return NextResponse.json(
        { error: 'Missing required fields' },
        { status: 400 }
      )
    }

    // 创建套餐
    const plan = await prisma.subscriptionPlan.create({
      data: {
        id,
        name,
        displayName,
        description,
        price,
        currency,
        interval,
        stripePriceId,
        isActive,
        sortOrder,
        features,
        limits
      }
    })

    return NextResponse.json({ plan })
  } catch (error) {
    console.error('Error creating subscription plan:', error)
    return NextResponse.json(
      { error: 'Failed to create subscription plan' },
      { status: 500 }
    )
  }
}

// PUT - 更新订阅套餐
export async function PUT(request: NextRequest) {
  try {
    const user = await verifyAdmin()
    if (!user) {
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
    }

    const {
      id,
      name,
      displayName,
      description,
      price,
      currency,
      interval,
      stripePriceId,
      isActive,
      sortOrder,
      features,
      limits
    } = await request.json()

    if (!id) {
      return NextResponse.json(
        { error: 'Plan ID is required' },
        { status: 400 }
      )
    }

    // 更新套餐
    const plan = await prisma.subscriptionPlan.update({
      where: { id },
      data: {
        ...(name && { name }),
        ...(displayName && { displayName }),
        ...(description !== undefined && { description }),
        ...(price !== undefined && { price }),
        ...(currency && { currency }),
        ...(interval && { interval }),
        ...(stripePriceId !== undefined && { stripePriceId }),
        ...(isActive !== undefined && { isActive }),
        ...(sortOrder !== undefined && { sortOrder }),
        ...(features && { features }),
        ...(limits && { limits })
      }
    })

    return NextResponse.json({ plan })
  } catch (error) {
    console.error('Error updating subscription plan:', error)
    return NextResponse.json(
      { error: 'Failed to update subscription plan' },
      { status: 500 }
    )
  }
}

// DELETE - 删除订阅套餐
export async function DELETE(request: NextRequest) {
  try {
    const user = await verifyAdmin()
    if (!user) {
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
    }

    const { searchParams } = new URL(request.url)
    const planId = searchParams.get('id')

    if (!planId) {
      return NextResponse.json(
        { error: 'Plan ID is required' },
        { status: 400 }
      )
    }

    // 检查是否有用户正在使用此套餐
    const usersCount = await prisma.user.count({
      where: { subscriptionPlanId: planId }
    })

    if (usersCount > 0) {
      return NextResponse.json(
        { error: 'Cannot delete plan with active users' },
        { status: 400 }
      )
    }

    // 删除套餐
    await prisma.subscriptionPlan.delete({
      where: { id: planId }
    })

    return NextResponse.json({ success: true })
  } catch (error) {
    console.error('Error deleting subscription plan:', error)
    return NextResponse.json(
      { error: 'Failed to delete subscription plan' },
      { status: 500 }
    )
  }
}
