/** * Google Gmail Integration (OAuth + scan trigger) */ import { NextRequest, NextResponse } from 'next/server' import { auth } from '@/auth' import { getGoogleOAuthCredentials, getGoogleTokens, readIntegrationMeta, writeIntegrationMeta, } from '@/lib/integrations/google-integration-tokens' import { gmailScannerService } from '@/lib/integrations/gmail-scanner.service' const GMAIL_SCOPE = 'https://www.googleapis.com/auth/gmail.readonly' const GOOGLE_AUTH_URL = 'https://accounts.google.com/o/oauth2/v2/auth' function redirectUri(origin: string) { return `${origin}/api/integrations/gmail/callback` } export async function GET(req: NextRequest) { const session = await auth() if (!session?.user?.id) { return NextResponse.json({ error: 'Unauthorized' }, { status: 401 }) } const url = new URL(req.url) const userId = session.user.id if (url.searchParams.get('connect') === '1') { const { clientId } = getGoogleOAuthCredentials() if (!clientId) { return NextResponse.json({ error: 'Google OAuth not configured' }, { status: 503 }) } const authUrl = new URL(GOOGLE_AUTH_URL) authUrl.searchParams.set('client_id', clientId) authUrl.searchParams.set('redirect_uri', redirectUri(url.origin)) authUrl.searchParams.set('response_type', 'code') authUrl.searchParams.set('scope', GMAIL_SCOPE) authUrl.searchParams.set('access_type', 'offline') authUrl.searchParams.set('prompt', 'consent') authUrl.searchParams.set('state', userId) return NextResponse.redirect(authUrl.toString()) } if (url.searchParams.get('scan') === '1') { const result = await gmailScannerService.scanUser(userId) return NextResponse.json(result) } const status = await gmailScannerService.getStatus(userId) return NextResponse.json(status) } export async function DELETE() { const session = await auth() if (!session?.user?.id) { return NextResponse.json({ error: 'Unauthorized' }, { status: 401 }) } const meta = await readIntegrationMeta(session.user.id) delete meta.gmailAccessToken delete meta.gmailRefreshToken await writeIntegrationMeta(session.user.id, meta) return NextResponse.json({ success: true }) }