import axios from "axios";
import queryString from "query-string";
import { DatabaseService } from "../services/databaseService";
import { GoogleOAuthOptions } from "../helpers/interface.types";

const dbService = DatabaseService.getInstance();

export const getAuthURLGoogle = (options: GoogleOAuthOptions) => {
  const params = queryString.stringify({
    client_id: options.clientId,
    redirect_uri: options.redirectUri,
    response_type: "code",
    scope: options.scope || 'openid email profile', // Default scope added
  });
  return `https://accounts.google.com/o/oauth2/v2/auth?${params}`;
};

export const getTokenGoogle = async (code: any, options: { clientId: any; clientSecret: any; redirectUri: any; }) => {
  const response = await axios.post(
    "https://oauth2.googleapis.com/token",
    queryString.stringify({
      client_id: options.clientId,
      client_secret: options.clientSecret,
      code,
      redirect_uri: options.redirectUri,
      grant_type: "authorization_code",
    }),
    { headers: { "Content-Type": "application/x-www-form-urlencoded" } }
  );
  return response.data.access_token;
};

export const getUserInfoGoogle = async (accessToken: any) => {
  const response = await axios.get("https://www.googleapis.com/oauth2/v1/userinfo", {
    headers: { Authorization: `Bearer ${accessToken}` },
  });
  return response.data;
};

export const handleGoogleCallback = async (code: string, options: { clientId: any; clientSecret: any; redirectUri: any; }) => {
  try {
    const accessToken = await getTokenGoogle(code, options);
    const profile = await getUserInfoGoogle(accessToken);

    // Now update the user's Google ID in the database
    const user = await dbService.findUserByEmail(profile.email);
    if (user) {
      await dbService.updateUser(user.id, { googleId: profile.id });
    }

    return profile;
  } catch (err) {
    throw err;
  }
};
