import type { APIRoute } from 'astro';
import { authService } from '@/lib/authService';
import type { AuthClient } from '@/lib/authService';
import { oauthStoreService } from '@/lib/oauthStore';

export const GET: APIRoute = async ({ request, redirect }) => {
    try {
        console.log('=== GOOGLE OAUTH INIT START ===');
        console.log('Google OAuth route hit');

        const pb: AuthClient = authService.createClientFromRequest(request);
        console.log('PocketBase client created');

        const authMethods = await pb.collection('users').listAuthMethods();
        console.log('Available OAuth providers:', authMethods.oauth2.providers.map(p => ({
            name: p.name,
            displayName: p.displayName,
            state: p.state,
            codeChallenge: p.codeChallenge,
            codeChallengeMethod: p.codeChallengeMethod,
            codeVerifier: p.codeVerifier ? 'VERIFIER_EXISTS' : 'VERIFIER_MISSING'
        })));

        const provider = authMethods.oauth2.providers.find(p => p.name === 'google');

        if (!provider) {
            console.log('Google provider not found');
            return new Response('No Google provider', { status: 400 });
        }

        console.log('Google provider found:', {
            name: provider.name,
            displayName: provider.displayName,
            state: provider.state,
            codeChallenge: provider.codeChallenge,
            codeChallengeMethod: provider.codeChallengeMethod,
            codeVerifierLength: provider.codeVerifier ? provider.codeVerifier.length : 0
        });

        // Извлекаем callbackUrl из параметров запроса
        const url = new URL(request.url);
        const callbackUrl = url.searchParams.get('callbackUrl') || '/bewertungen'; // по умолчанию - страница отзывов

        // Сохраняем verifier и callbackUrl в наше серверное хранилище
        console.log('Saving verifier and callbackUrl to server storage for state:', provider.state);
        oauthStoreService.set(provider.state, provider.codeVerifier, callbackUrl);
        console.log('Verifier and callbackUrl saved to server storage successfully');

        // Ссылка возврата (как в Google Console)
        const redirectUrl = 'http://localhost:3000/api/auth/google/callback';

        console.log('Using provider authURL (before modification):', provider.authURL);

        const authUrl = new URL(provider.authURL);
        authUrl.searchParams.set('redirect_uri', redirectUrl);

        console.log('Final auth URL with redirect:', authUrl.toString());
        console.log('=== GOOGLE OAUTH INIT END ===');

        return redirect(authUrl.toString());

    } catch (error) {
        console.error('OAuth Google Init Error:', error);
        return new Response('Auth Error', { status: 500 });
    }
};