// Server-only helpers for Google sign-in. The OAuth client (id/secret) comes from
// the backend (Admin Settings → Credentials → Google Auth) with an env fallback;
// the allow-list + roles come from the Users & Roles directory (lookupUser).
// Never import this from a client component.

const BACKEND = process.env.BACKEND_INTERNAL_URL || "http://127.0.0.1:8000";
const TOKEN = process.env.ADMIN_API_TOKEN || "";

export type GoogleClient = { clientId: string; clientSecret: string };

export async function resolveGoogleAuth(): Promise<GoogleClient> {
  let clientId = "";
  let clientSecret = "";
  try {
    const res = await fetch(`${BACKEND}/api/google-auth/resolve`, {
      headers: { Authorization: `Bearer ${TOKEN}` },
      cache: "no-store",
    });
    if (res.ok) {
      const j = await res.json();
      clientId = typeof j.clientId === "string" ? j.clientId : "";
      clientSecret = typeof j.clientSecret === "string" ? j.clientSecret : "";
    }
  } catch {
    // fall back to env below
  }
  return {
    clientId: clientId || process.env.GOOGLE_CLIENT_ID || "",
    clientSecret: clientSecret || process.env.GOOGLE_CLIENT_SECRET || "",
  };
}

export type UserLookup = { found: boolean; anyAllowed: boolean; name: string | null; roles: string[] };

/** Resolve a (Google-verified) email against the Users & Roles directory. */
export async function lookupUser(email: string): Promise<UserLookup> {
  try {
    const res = await fetch(`${BACKEND}/api/users/lookup?email=${encodeURIComponent(email)}`, {
      headers: { Authorization: `Bearer ${TOKEN}` },
      cache: "no-store",
    });
    if (res.ok) {
      const j = await res.json();
      return {
        found: !!j.found,
        anyAllowed: !!j.anyAllowed,
        name: typeof j.name === "string" ? j.name : null,
        roles: Array.isArray(j.roles) ? j.roles.map(String) : [],
      };
    }
  } catch {
    // treat as not found
  }
  return { found: false, anyAllowed: false, name: null, roles: [] };
}
