import { buildAttachmentUploadFormData, toAttachmentUploadDescriptor, uploadAttachmentToServerApi, } from "@superblocksteam/shared";
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, fileName, prefix = "message-attachment", metadata, branchId, commitId, useServerUpload = false, superblocksBaseUrl, jwt, logger, }) {
    const descriptor = toAttachmentUploadDescriptor(file, {
        fallbackFileName: fileName,
    });
    if (!descriptor) {
        throw new Error("Unsupported attachment upload input");
    }
    const buildFormData = () => {
        return buildAttachmentUploadFormData({
            descriptor,
            prefix,
            metadata,
            branchId,
            commitId,
        });
    };
    const uploadViaServer = async () => {
        const payload = await uploadAttachmentToServerApi({
            baseUrl: superblocksBaseUrl,
            authorization: `Bearer ${jwt}`,
            descriptor,
            scopeType: "app",
            purpose: "attachment",
            applicationId,
            branchName: branchId,
            commitId,
            prefix,
            metadata,
        });
        return {
            fileName: payload.fileName || descriptor.fileName,
            url: payload.contentUrl ?? payload.signedUrl,
            expirationDate: Math.floor(new Date(payload.signedUrlExpiresAt).getTime() / 1000),
            mimeType: (typeof payload.mimeType === "string" && payload.mimeType.trim()) ||
                descriptor.mimeType,
            storageKey: payload.storageKey,
            scopeType: payload.scopeType,
            applicationId: payload.applicationId,
        };
    };
    const uploadViaBucketeer = async () => {
        let scopedToken;
        try {
            scopedToken = await getScopedToken({
                applicationId,
                superblocksBaseUrl,
                jwt,
            });
        }
        catch (error) {
            logger.error("[uploadAttachmentToBucketeer] Failed to get scoped token", getErrorMeta(error));
            throw error;
        }
        const bucketeerUrl = getBucketeerUrlFromSuperblocksUrl(superblocksBaseUrl);
        const uploadUrl = `${bucketeerUrl}/applications/${applicationId}/attachments`;
        const response = await fetch(uploadUrl, {
            method: "POST",
            body: buildFormData(),
            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 || descriptor.fileName,
            url: result.url,
            expirationDate: result.expirationDate,
            mimeType: descriptor.mimeType,
        };
    };
    if (useServerUpload) {
        try {
            return await uploadViaServer();
        }
        catch (error) {
            logger.warn("[uploadAttachmentToBucketeer] Server upload failed, falling back to Bucketeer", getErrorMeta(error));
        }
    }
    return uploadViaBucketeer();
}
//# sourceMappingURL=attachment-upload.js.map