import { cookies } from 'next/headers';
import { NextResponse } from 'next/server';
import { ServiceFactory } from '@/lib/services/ServiceFactory';

const STATE_COOKIE = 'gp_demo_auth_state';

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

  if (!code || !state) {
    return NextResponse.redirect('/auth/iracing');
  }

  const cookieStore = await cookies();
  const storedState = cookieStore.get(STATE_COOKIE)?.value;

  if (!storedState || storedState !== state) {
    return NextResponse.redirect('/auth/iracing');
  }

  const serviceFactory = new ServiceFactory(process.env.NEXT_PUBLIC_API_BASE_URL || 'http://localhost:3001');
  const authService = serviceFactory.createAuthService();
  const loginInput = returnTo ? { code, state, returnTo } : { code, state };
  await authService.loginWithIracingCallback(loginInput);

  cookieStore.delete(STATE_COOKIE);

  const redirectTarget = returnTo || '/dashboard';
  const absoluteRedirect = new URL(redirectTarget, url.origin).toString();
  return NextResponse.redirect(absoluteRedirect);
}