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

export async function GET(request: NextRequest) {
  const searchParams = request.nextUrl.searchParams;
  const code = searchParams.get('code');

  if (!code) {
    return NextResponse.redirect(new URL('/login?error=no_code', request.url));
  }

  try {
    const { user, accessToken, refreshToken } = await workos.userManagement.authenticateWithCode({
      clientId,
      code,
    });

    // Get the stay logged in preference
    const cookieStore = await cookies();
    const stayLoggedInCookie = cookieStore.get('stay_logged_in');
    const stayLoggedIn = stayLoggedInCookie?.value === 'true';

    // Clear the temporary cookie
    cookieStore.delete('stay_logged_in');

    await setSession({
      user: {
        id: user.id,
        email: user.email,
        firstName: user.firstName,
        lastName: user.lastName,
        profilePictureUrl: user.profilePictureUrl,
      },
      accessToken,
      refreshToken,
      stayLoggedIn,
    });

    return NextResponse.redirect(new URL('/', request.url));
  } catch (error) {
    console.error('Auth callback error:', error);
    return NextResponse.redirect(new URL('/login?error=auth_failed', request.url));
  }
}
