import { google } from "googleapis";
import { loadGoogleTokens, saveGoogleTokens } from "../config/index.js";
import { resolveGoogleOAuthCredentials } from "../google/oauth-credentials.js";
import { logger } from "../logger.js";
/**
 * Wrapper around Google Meet REST API v2.
 * Used to configure meeting spaces (e.g. set accessType to OPEN so
 * participants can join without a waiting room/lobby).
 */
export class GoogleMeetClient {
    meet;
    constructor(config) {
        const tokens = loadGoogleTokens();
        const { clientId, clientSecret } = resolveGoogleOAuthCredentials(config);
        const oauth2Client = new google.auth.OAuth2(clientId, clientSecret);
        oauth2Client.setCredentials({
            access_token: tokens.access_token,
            refresh_token: tokens.refresh_token,
            token_type: tokens.token_type,
            expiry_date: tokens.expiry_date,
        });
        // Auto-refresh tokens
        oauth2Client.on("tokens", (newTokens) => {
            const existing = loadGoogleTokens();
            saveGoogleTokens({
                ...existing,
                access_token: newTokens.access_token ?? existing.access_token,
                refresh_token: newTokens.refresh_token ?? existing.refresh_token,
                expiry_date: newTokens.expiry_date ?? existing.expiry_date,
            });
        });
        this.meet = google.meet({ version: "v2", auth: oauth2Client });
    }
    /**
     * Set a Meet space's accessType to OPEN so anyone with the link can join
     * without waiting in a lobby/waiting room.
     *
     * The spaces.patch endpoint requires the canonical space name
     * (e.g. "spaces/jQCFfuBOdN5z"), not the meeting code. This method
     * resolves the meeting code first via spaces.get, then patches.
     *
     * @param meetingCode - The meeting code from the hangoutLink URL
     *   (e.g. "abc-defg-hij" from "https://meet.google.com/abc-defg-hij")
     */
    async setSpaceAccessOpen(meetingCode) {
        // Resolve the meeting code to the canonical space name
        const getRes = await this.meet.spaces.get({
            name: `spaces/${meetingCode}`,
        });
        const spaceName = getRes.data.name;
        if (!spaceName) {
            logger.warn("Meet space has no canonical name, falling back to meeting code", {
                meetingCode,
            });
        }
        await this.meet.spaces.patch({
            name: spaceName ?? `spaces/${meetingCode}`,
            updateMask: "config.accessType",
            requestBody: {
                config: { accessType: "OPEN" },
            },
        });
    }
}
//# sourceMappingURL=google-meet.js.map