import {wrapper} from '@/lib/server/utils/apiWrapper'
import {NextResponse} from 'next/server'
import {OAuth2Client, TokenPayload} from 'google-auth-library'
const client = new OAuth2Client()
import DAL from '@dal'
import {createJwtToken} from '@/lib/server/utils/jwtUtils'

export const GET = wrapper(async (request): Promise<NextResponse> => {
  const googleToken = request.headers.get('authorization')?.split(' ')[1]

  if (!googleToken) {
    return new NextResponse(JSON.stringify({error: 'Unauthorized'}), {status: 401})
  }

  const ticket = await client.verifyIdToken({
    idToken: googleToken,
    audience: process.env.GOOGLE_WEB_CLIENT_ID,
  })

  if (!ticket) {
    return new NextResponse(JSON.stringify({error: 'Unauthorized'}), {status: 401})
  }

  const payload = ticket.getPayload() as TokenPayload

  // Check if the user is already in the database, if not it should be created.
  let user = await DAL.getUserByGoogleId(payload.sub)

  if (!user) {
    user = await DAL.createSocialUser({
      email: payload.email!,
      username: payload.name ?? payload.email!.split('@')[0],
      googleId: payload.sub,
    })
  }

  const token = createJwtToken(user);

  return new NextResponse(JSON.stringify({token}), {status: 200})
}, false)
