import { NextResponse } from 'next/server' import { cookies } from 'next/headers' import { exchangeGoogleCode } from '@/lib/google-oauth' import { createMemberSession } from '@/lib/member-auth' import { prisma } from '@/lib/db' const SITE_URL = process.env.NEXT_PUBLIC_SITE_URL || 'https://lotoloki.top' function safeNext(raw: string): string { return raw.startsWith('/') && !raw.startsWith('//') ? raw : '/' } export async function GET(req: Request) { const url = new URL(req.url) const origin = SITE_URL const code = url.searchParams.get('code') const state = url.searchParams.get('state') const jar = await cookies() const savedState = jar.get('g_state')?.value if (!code || !state || state !== savedState) { return NextResponse.redirect(`${origin}/connexion?error=oauth_state`) } const next = safeNext(decodeURIComponent(state.split('.')[1] ?? '/')) const profile = await exchangeGoogleCode(code) if (!profile?.email) { return NextResponse.redirect(`${origin}/connexion?error=oauth_failed`) } const email = profile.email.toLowerCase() const user = await prisma.user.upsert({ where: { googleSub: profile.sub }, update: { email, name: profile.name || email.split('@')[0], avatarUrl: profile.picture ?? null }, create: { email, name: profile.name || email.split('@')[0], avatarUrl: profile.picture ?? null, googleSub: profile.sub }, }) await createMemberSession(user.id) const res = NextResponse.redirect(`${origin}${next}`) res.cookies.delete('g_state') return res }