import { OAuth2Client } from 'google-auth-library';

const client = new OAuth2Client(
    process.env.GOOGLE_CLIENT_ID,
    process.env.GOOGLE_CLIENT_SECRET,
    process.env.GOOGLE_REDIRECT_URI
);

export function getGoogleAuthUrl() {
    return client.generateAuthUrl({
        access_type: 'offline',
        scope: [
            'https://www.googleapis.com/auth/userinfo.profile',
            'https://www.googleapis.com/auth/userinfo.email',
        ],
        prompt: 'consent'
    });
}

export interface GoogleUserProfile {
    sub: string;
    email: string;
    name: string;
    picture?: string;
}

export async function getGoogleUser(code: string): Promise<GoogleUserProfile> {
    const { tokens } = await client.getToken(code);
    client.setCredentials(tokens);

    const userInfo = await fetch('https://www.googleapis.com/oauth2/v3/userinfo', {
        headers: { Authorization: `Bearer ${tokens.access_token}` },
    }).then(res => res.json()) as GoogleUserProfile;

    return userInfo;
}
