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

const VALID_PROVIDERS = ['GoogleOAuth', 'AppleOAuth', 'GitHubOAuth'];

export async function GET(request: NextRequest) {
  try {
    const searchParams = request.nextUrl.searchParams;
    const provider = searchParams.get('provider') as OAuthProvider | 'authkit' | null;
    const stayLoggedIn = searchParams.get('stayLoggedIn') === 'true';

    // 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: '/',
    });

    // If no provider or 'authkit', redirect to hosted AuthKit (email/password, phone)
    if (!provider || provider === 'authkit') {
      const authUrl = getAuthKitUrl();
      console.log('AuthKit URL generated:', authUrl);

      if (!authUrl || typeof authUrl !== 'string') {
        return NextResponse.json({
          error: 'Failed to generate AuthKit URL',
          debug: { authUrl, hasClientId: !!process.env.WORKOS_CLIENT_ID, hasRedirectUri: !!process.env.WORKOS_REDIRECT_URI }
        }, { status: 500 });
      }

      return NextResponse.redirect(authUrl);
    }

    // Validate OAuth provider
    if (!VALID_PROVIDERS.includes(provider)) {
      return NextResponse.json({ error: 'Invalid provider' }, { status: 400 });
    }

    const authUrl = getAuthorizationUrl(provider);
    return NextResponse.redirect(authUrl);
  } catch (error) {
    console.error('Login route error:', error);
    return NextResponse.json({
      error: 'Authentication error',
      message: String(error)
    }, { status: 500 });
  }
}
