import { google } from "@/auth/oauth";
import { cookies } from "next/headers";
import { NextRequest, NextResponse } from "next/server";
import { prisma } from '@/lib/prisma'
import { createSession } from "@/auth/lucia";
type GoogleUser = {
    id: string,
    email: string,
    verified_email: boolean,
    name: string,
    given_name: string,
    picture: string,
    locale: string,
    family_name: string
}

export const GET = async (req: NextRequest) => {
    try {
        const url = new URL(req.url)
        const searchParams = url.searchParams
        const state = searchParams.get('state')
        const code = searchParams.get('code')
        if (!code || !state) {
            return Response.json({ error: "Invalid request" }, { status: 400 })
        }
        const codeVarifier = cookies().get('codeVerifier')?.value
        const saveState = cookies().get('state')?.value
        console.log('codeVarifier------------>', codeVarifier);
        if (!codeVarifier || !saveState) {
            return Response.json({ error: "Invalid request" }, { status: 400 })
        }
        if (saveState !== state) {
            return Response.json({ error: "State Doesn't Match" }, { status: 400 })
        }
        console.log('codeVarifier------------>', saveState, state, code, codeVarifier);

        // const { accessToken, idToken, refreshToken, accessTokenExpiresAt } = await google.validateAuthorizationCode(code, codeVarifier)
        const { accessToken, idToken, refreshToken, accessTokenExpiresAt } = await google.validateAuthorizationCode(code, codeVarifier)
        console.log('accessToken------------>', accessToken);
        const googleRes = await fetch("https://www.googleapis.com/oauth2/v1/userinfo", {
            cache: 'no-cache',
            headers: {
                Authorization: `Bearer ${accessToken}`
            },
            method: 'GET'
        },)
        const googleData = (await googleRes.json()) as GoogleUser
        console.log(googleData);
        const savedUser = await prisma?.user?.findUnique({
            where: {
                email: googleData?.email
            }
        })
        if (savedUser) {
            await createSession(savedUser.id)
        } else {

            const createdUser = await prisma?.user?.create(
                {
                    data: {
                        id: googleData?.id,
                        email: googleData?.email,
                        provider: 'google',
                        imageUrl: googleData?.picture,
                        imageName: googleData?.picture,
                        firstName: googleData?.given_name,
                        lastName: googleData?.family_name,
                        otherInfo: {
                            language: googleData?.locale
                        }
                    }
                }
            )
            await createSession(createdUser.id)
        }
        return NextResponse.redirect(new URL(process.env.WEBSITE_URL ?? '/'), { status: 302 })

    } catch (error) {
        return Response.json({
            error: error?.message
        })
    }
}