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

export async function POST() {
  try {
    // 验证用户身份
    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 NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
    }

    // 获取用户的实时订阅状态
    const subscriptionStatus = await SubscriptionService.getUserSubscriptionStatus(user.id)

    // 更新用户的订阅套餐
    await SubscriptionService.updateUserSubscriptionPlan(user.id, subscriptionStatus.planId)

    // 获取用户权益
    const permissions = await SubscriptionService.getUserPermissions(user.id)

    console.log(`Synced user ${user.id} subscription to ${subscriptionStatus.planId}`)

    return NextResponse.json({
      success: true,
      subscription: subscriptionStatus,
      permissions: permissions
    })

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