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

// GET - 获取用户订阅信息
export async function GET() {
  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)
    const permissions = await SubscriptionService.getUserPermissions(user.id)

    // 获取套餐信息
    const plan = await SubscriptionService.getPlanById(subscriptionStatus.planId)

    return NextResponse.json({
      subscription: subscriptionStatus,
      permissions: permissions,
      plan: plan ? {
        id: plan.id,
        displayName: plan.displayName,
        price: plan.price
      } : null
    })

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

// POST - 管理订阅（取消、重新激活等）
export async function POST(request: NextRequest) {
  try {
    const { action, subscriptionId } = await request.json()

    // 验证用户身份 - 使用服务器端客户端
    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)

    if (!subscriptionStatus.stripeSubscriptionId) {
      return NextResponse.json({ error: 'No active subscription found' }, { status: 404 })
    }

    let result

    switch (action) {
      case 'cancel':
        result = await cancelSubscription(subscriptionId)
        break
      case 'reactivate':
        result = await reactivateSubscription(subscriptionId)
        break
      case 'portal':
        try {
          // 获取用户的 Stripe 客户 ID
          const userData = await prisma.user.findUnique({
            where: { id: user.id },
            select: { stripeCustomerId: true }
          })

          if (!userData?.stripeCustomerId) {
            return NextResponse.json({ error: 'No customer found' }, { status: 404 })
          }

          result = await createCustomerPortalSession(
            userData.stripeCustomerId,
            `${process.env.NEXT_PUBLIC_APP_URL}/subscription`
          )
          return NextResponse.json({ url: result.url })
        } catch (portalError) {
          console.error('Portal creation error:', portalError)
          return NextResponse.json({
            error: 'Failed to create portal session',
            details: portalError instanceof Error ? portalError.message : 'Unknown error'
          }, { status: 500 })
        }
      default:
        return NextResponse.json({ error: 'Invalid action' }, { status: 400 })
    }

    return NextResponse.json({ 
      success: true, 
      subscription: {
        id: result.id,
        status: result.status,
        cancelAtPeriodEnd: result.cancel_at_period_end
      }
    })

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