import { getBucketeerUrlFromSuperblocksUrl } from "@superblocksteam/util";
import { getErrorMeta } from "../util/logger.js";
import { getScopedToken } from "./util/scoped-token-utils.js";
/**
 * Uploads a file to Bucketeer's generic attachments endpoint.
 */
export async function uploadAttachmentToBucketeer({ applicationId, file, prefix = "message-attachment", branchId, commitId, superblocksBaseUrl, jwt, logger, }) {
    let scopedToken;
    try {
        scopedToken = await getScopedToken({
            applicationId,
            superblocksBaseUrl,
            jwt,
        });
    }
    catch (error) {
        logger.error("[uploadAttachmentToBucketeer] Failed to get scoped token", getErrorMeta(error));
        throw error;
    }
    let blob;
    let mimeType;
    if (file instanceof File || file instanceof Blob) {
        blob = file;
        mimeType = file.type || "application/octet-stream";
    }
    else {
        const isDataUrl = typeof file.data === "string" && file.data.includes(",");
        let base64Data;
        if (isDataUrl) {
            const parts = file.data.split(",");
            const mimePart = parts[0];
            base64Data = parts[1] || "";
            const mimeMatch = mimePart?.match(/data:([^;]+)/);
            mimeType = mimeMatch?.[1] || file.mimeType || "application/octet-stream";
        }
        else {
            base64Data = file.data;
            mimeType = file.mimeType || "application/octet-stream";
        }
        const binaryData = Uint8Array.from(atob(base64Data), (c) => c.charCodeAt(0));
        blob = new Blob([binaryData], { type: mimeType });
    }
    const formData = new FormData();
    formData.append("file", blob);
    formData.append("prefix", prefix);
    if (branchId) {
        formData.append("branchId", branchId);
    }
    if (commitId) {
        formData.append("commitId", commitId);
    }
    const bucketeerUrl = getBucketeerUrlFromSuperblocksUrl(superblocksBaseUrl);
    const uploadUrl = `${bucketeerUrl}/applications/${applicationId}/attachments`;
    const response = await fetch(uploadUrl, {
        method: "POST",
        body: formData,
        headers: {
            Authorization: `Bearer ${scopedToken}`,
        },
    });
    if (!response.ok) {
        const errorText = await response
            .text()
            .catch(() => "Unable to read error response");
        logger.error(`[uploadAttachmentToBucketeer] Upload failed: status=${response.status}, error=${errorText}`);
        throw new Error(`Attachment upload failed: ${response.statusText}`);
    }
    const result = (await response.json());
    return {
        fileName: result.fileName,
        url: result.url,
        expirationDate: result.expirationDate,
    };
}
//# sourceMappingURL=attachment-upload.js.map