import { NextResponse } from 'next/server'
import { prisma } from '@/lib/prisma'
import { createServerSupabaseClient } from '@/lib/supabase-server'
import { addSystemGiftCredit } from '@/lib/credits'

// POST /api/users/sync - 同步Supabase用户到Prisma数据库
export async function POST() {
  try {
    const supabase = await createServerSupabaseClient()
    const { data: { user: supabaseUser }, error: authError } = await supabase.auth.getUser()

    if (authError || !supabaseUser) {
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
    }

    // 检查用户是否已存在于Prisma数据库中
    const existingUser = await prisma.user.findUnique({
      where: { id: supabaseUser.id }
    })

    if (existingUser) {
      // 用户已存在，更新信息
      const updatedUser = await prisma.user.update({
        where: { id: supabaseUser.id },
        data: {
          email: supabaseUser.email!,
          username: supabaseUser.user_metadata?.username || supabaseUser.user_metadata?.full_name || null,
          avatar: supabaseUser.user_metadata?.avatar_url || null,
          bio: supabaseUser.user_metadata?.bio || null,
          language: supabaseUser.user_metadata?.language || 'en',
          updatedAt: new Date()
        }
      })
      
      return NextResponse.json({ 
        message: 'User updated successfully', 
        user: updatedUser 
      })
    } else {
      // 用户不存在，创建新用户
      const newUser = await prisma.user.create({
        data: {
          id: supabaseUser.id,
          email: supabaseUser.email!,
          username: supabaseUser.user_metadata?.username || supabaseUser.user_metadata?.full_name || null,
          avatar: supabaseUser.user_metadata?.avatar_url || null,
          bio: supabaseUser.user_metadata?.bio || null,
          language: supabaseUser.user_metadata?.language || 'en'
        }
      })

      // 为新用户添加系统赠送的5USD信用额度（1个月后过期）
      await addSystemGiftCredit(newUser.id)

      return NextResponse.json({ 
        message: 'User created successfully', 
        user: newUser 
      }, { status: 201 })
    }

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

// GET /api/users/sync - 获取当前用户信息
export async function GET() {
  try {
    const supabase = await createServerSupabaseClient()
    const { data: { user: supabaseUser }, error: authError } = await supabase.auth.getUser()

    if (authError || !supabaseUser) {
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
    }

    // 从Prisma数据库获取用户信息
    const user = await prisma.user.findUnique({
      where: { id: supabaseUser.id }
    })

    if (!user) {
      return NextResponse.json({ error: 'User not found in database' }, { status: 404 })
    }

    return NextResponse.json({ user })

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