import { ApolloServer } from '@apollo/server'
import { startServerAndCreateNextHandler } from '@as-integrations/next'
import { NextRequest } from 'next/server'
import jwt from 'jsonwebtoken'
import { typeDefs } from '@/graphql/typedefs'
import { resolvers } from '@/graphql/resolvers'

// Интерфейс для контекста
interface Context {
  user?: {
    id: string
    phone: string
  }
  admin?: {
    id: string
    username: string
  }
}

// Создаем Apollo Server
const server = new ApolloServer<Context>({
  typeDefs,
  resolvers,
})

// Создаем Next.js handler
const handler = startServerAndCreateNextHandler<NextRequest>(server, {
  context: async (req: NextRequest) => {
    // Извлекаем токен из заголовка Authorization
    const authHeader = req.headers.get('authorization')
    const token = authHeader?.replace('Bearer ', '')

    console.log('GraphQL Context - Auth header:', authHeader)
    console.log('GraphQL Context - Token:', token ? `${token.substring(0, 20)}...` : 'No token')

    if (!token) {
      console.log('GraphQL Context - No token provided')
      return { user: undefined, admin: undefined }
    }

    try {
      // Верифицируем JWT токен
      const decoded = jwt.verify(token, process.env.JWT_SECRET!) as {
        userId?: string
        phone?: string
        adminId?: string
        username?: string
        type?: string
      }

      // Проверяем тип токена
      if (decoded.type === 'admin' && decoded.adminId && decoded.username) {
        console.log('GraphQL Context - Decoded admin:', { id: decoded.adminId, username: decoded.username })
        return {
          admin: {
            id: decoded.adminId,
            username: decoded.username
          }
        }
      } else if (decoded.userId && decoded.phone) {
        console.log('GraphQL Context - Decoded user:', { id: decoded.userId, phone: decoded.phone })
        return {
          user: {
            id: decoded.userId,
            phone: decoded.phone
          }
        }
      }

      return { user: undefined, admin: undefined }
    } catch (error) {
      console.error('GraphQL Context - Invalid token:', error)
      return { user: undefined, admin: undefined }
    }
  }
})

export async function GET(request: NextRequest) {
  return handler(request)
}

export async function POST(request: NextRequest) {
  return handler(request)
} 