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

import { Context } from '@/graphql/context'
import { resolvers } from '@/graphql/resolvers'
import { typeDefs } from '@/graphql/typedefs'
import { prisma } from '@/lib/prisma'

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

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

    if (!token) {
      return { user: null, admin: null, prisma }
    }

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

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

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

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

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