import { cookies } from 'next/headers';
import { NextResponse } from 'next/server';

export async function GET(request: Request) {
  const url = new URL(request.url);
  const returnTo = url.searchParams.get('returnTo') ?? undefined;

  const redirectUrl = `https://example.com/iracing/auth?returnTo=${encodeURIComponent(returnTo || '')}`;
  // For now, generate a simple state - in production this should be cryptographically secure
  const state = Math.random().toString(36).substring(2, 15);

  const cookieStore = await cookies();
  cookieStore.set('gp_demo_auth_state', state, {
    httpOnly: true,
    sameSite: 'lax',
    path: '/',
    secure: process.env.NODE_ENV === 'production',
  });

  const absoluteRedirect = new URL(redirectUrl, url.origin).toString();
  return NextResponse.redirect(absoluteRedirect);
}