import { google } from "googleapis";
import { OAuth2Client } from "google-auth-library";
import { getGoogleConfig } from "./config-store";

// Scopes demandés (cf. 05_INTEGRATION_GOOGLE.md). Permissions minimales pour le MVP :
// - Calendar : lecture + écriture d'événements
// - Gmail    : lire / trier / archiver (gmail.modify) — pas d'envoi pour l'instant
// - openid/email/profile : identifier le compte Google lié
export const GOOGLE_SCOPES = [
  "openid",
  "email",
  "profile",
  "https://www.googleapis.com/auth/calendar",
  "https://www.googleapis.com/auth/gmail.modify",
  "https://www.googleapis.com/auth/drive",
];

// La config Google (client id/secret/redirect) vient de la base (réglages Super Admin),
// avec repli sur le .env. Ces fonctions sont donc asynchrones.
export async function makeOAuthClient(): Promise<OAuth2Client> {
  const c = await getGoogleConfig();
  return new google.auth.OAuth2(c.clientId, c.clientSecret, c.redirectUri);
}

// Client prêt à appeler les APIs au nom de l'utilisateur (rafraîchit l'access token tout seul).
export async function oauthClientForRefreshToken(refreshToken: string): Promise<OAuth2Client> {
  const client = await makeOAuthClient();
  client.setCredentials({ refresh_token: refreshToken });
  return client;
}

export async function isGoogleConfigured(): Promise<boolean> {
  const c = await getGoogleConfig();
  return Boolean(c.clientId && c.clientSecret);
}
