import crypto from "node:crypto";
import { google } from "googleapis";
const DIRECTORY_SCOPES = [
    "https://www.googleapis.com/auth/admin.directory.user",
    "https://www.googleapis.com/auth/apps.licensing",
];
function generateStrongPassword() {
    return crypto.randomBytes(24).toString("base64url");
}
function getWorkspaceEmail(spec) {
    return `${spec.emailUsername}@${spec.workspaceDomain}`;
}
function requireGoogleWorkspaceConfig(spec) {
    if (!spec.googleWorkspace) {
        throw new Error("googleWorkspace Admin SDK config is required for legacy client-side Workspace operations");
    }
    return spec.googleWorkspace;
}
function splitDisplayName(fullName) {
    const parts = fullName.trim().split(/\s+/).filter(Boolean);
    if (parts.length === 0) {
        return { givenName: "VisionClaw", familyName: "Agent" };
    }
    if (parts.length === 1) {
        return { givenName: parts[0], familyName: parts[0] };
    }
    return {
        givenName: parts[0],
        familyName: parts.slice(1).join(" "),
    };
}
async function getAccessToken(spec) {
    const googleWorkspace = requireGoogleWorkspaceConfig(spec);
    const delegatedAdminEmail = googleWorkspace.delegatedAdminEmail.trim();
    if (!delegatedAdminEmail) {
        throw new Error("googleWorkspace.delegatedAdminEmail is required for Workspace provisioning");
    }
    const jwt = new google.auth.JWT({
        email: googleWorkspace.adminSdkServiceAccount.client_email,
        key: googleWorkspace.adminSdkServiceAccount.private_key,
        scopes: DIRECTORY_SCOPES,
        subject: delegatedAdminEmail,
    });
    const token = await jwt.getAccessToken();
    if (!token.token) {
        throw new Error("Failed to obtain Google Admin SDK access token");
    }
    return token.token;
}
async function getWorkspaceUser(spec, email) {
    const token = await getAccessToken(spec);
    const response = await fetch(`https://admin.googleapis.com/admin/directory/v1/users/${encodeURIComponent(email)}`, {
        headers: {
            Authorization: `Bearer ${token}`,
        },
        signal: AbortSignal.timeout(30_000),
    });
    if (response.status === 404) {
        return null;
    }
    if (!response.ok) {
        const body = await response.text();
        throw new Error(`Failed to fetch Google Workspace user: HTTP ${response.status} ${body}`);
    }
    return response;
}
async function createWorkspaceUser(spec, email, password) {
    const token = await getAccessToken(spec);
    const name = splitDisplayName(spec.agentName);
    const response = await fetch("https://admin.googleapis.com/admin/directory/v1/users", {
        method: "POST",
        headers: {
            Authorization: `Bearer ${token}`,
            "Content-Type": "application/json",
        },
        body: JSON.stringify({
            primaryEmail: email,
            password,
            changePasswordAtNextLogin: false,
            suspended: false,
            name,
        }),
        signal: AbortSignal.timeout(30_000),
    });
    if (!response.ok) {
        const body = await response.text();
        throw new Error(`Failed to create Google Workspace user: HTTP ${response.status} ${body}`);
    }
}
async function assignLicense(spec, email) {
    const googleWorkspace = requireGoogleWorkspaceConfig(spec);
    const skuId = googleWorkspace.licenseSku?.trim();
    if (!skuId) {
        return;
    }
    const productId = googleWorkspace.licenseProductId?.trim() ?? "Google-Apps";
    const token = await getAccessToken(spec);
    const response = await fetch(`https://licensing.googleapis.com/apps/licensing/v1/product/${encodeURIComponent(productId)}/sku/${encodeURIComponent(skuId)}/user`, {
        method: "POST",
        headers: {
            Authorization: `Bearer ${token}`,
            "Content-Type": "application/json",
        },
        body: JSON.stringify({ userId: email }),
        signal: AbortSignal.timeout(30_000),
    });
    if (response.ok || response.status === 409) {
        return;
    }
    const body = await response.text();
    throw new Error(`Failed to assign Google Workspace license: HTTP ${response.status} ${body}`);
}
export async function resetWorkspaceUserPassword(spec, email, password) {
    const token = await getAccessToken(spec);
    const response = await fetch(`https://admin.googleapis.com/admin/directory/v1/users/${encodeURIComponent(email)}`, {
        method: "PATCH",
        headers: {
            Authorization: `Bearer ${token}`,
            "Content-Type": "application/json",
        },
        body: JSON.stringify({ password, changePasswordAtNextLogin: false }),
        signal: AbortSignal.timeout(30_000),
    });
    if (!response.ok) {
        const body = await response.text();
        throw new Error(`Failed to reset Google Workspace user password: HTTP ${response.status} ${body}`);
    }
}
export async function provisionWorkspaceAccount(spec, existingPassword) {
    const email = getWorkspaceEmail(spec);
    const password = spec.gmailPassword?.trim() ?? existingPassword ?? generateStrongPassword();
    const existing = await getWorkspaceUser(spec, email);
    if (!existing) {
        await createWorkspaceUser(spec, email, password);
        await assignLicense(spec, email);
        return { email, password, existed: false };
    }
    return { email, password, existed: true };
}
/**
 * Set the Google Workspace user's profile photo via the Admin SDK.
 * The image is resized by Google; the raw file should ideally be under 32 KB.
 */
export async function setWorkspaceUserPhoto(spec, email, photoBuffer) {
    const token = await getAccessToken(spec);
    const photoData = photoBuffer
        .toString("base64")
        .replace(/\+/g, "-")
        .replace(/\//g, "_")
        .replace(/=+$/, "");
    const response = await fetch(`https://admin.googleapis.com/admin/directory/v1/users/${encodeURIComponent(email)}/photos/thumbnail`, {
        method: "PUT",
        headers: {
            Authorization: `Bearer ${token}`,
            "Content-Type": "application/json",
        },
        body: JSON.stringify({ photoData }),
        signal: AbortSignal.timeout(30_000),
    });
    if (!response.ok) {
        const body = await response.text();
        throw new Error(`Failed to set Workspace user photo: HTTP ${response.status} ${body}`);
    }
}
//# sourceMappingURL=provision-workspace-account.js.map