import { NextRequest, NextResponse } from 'next/server';
import { getAuthorizationUrl } from '@/lib/workos';
import { cookies } from 'next/headers';

export async function GET(request: NextRequest) {
  const searchParams = request.nextUrl.searchParams;
  const provider = searchParams.get('provider') as 'GoogleOAuth' | 'AppleOAuth';
  const stayLoggedIn = searchParams.get('stayLoggedIn') === 'true';

  if (!provider || !['GoogleOAuth', 'AppleOAuth'].includes(provider)) {
    return NextResponse.json({ error: 'Invalid provider' }, { status: 400 });
  }

  // Store the stay logged in preference in a cookie
  const cookieStore = await cookies();
  cookieStore.set('stay_logged_in', stayLoggedIn.toString(), {
    httpOnly: true,
    secure: process.env.NODE_ENV === 'production',
    sameSite: 'lax',
    maxAge: 60 * 10, // 10 minutes for the auth flow
    path: '/',
  });

  const authUrl = getAuthorizationUrl(provider);
  return NextResponse.redirect(authUrl);
}
