import { toast } from "sonner";
const read = (raw, lower, pascal) => raw[lower] ?? raw[pascal];
const readString = (raw, lower, pascal) => {
    const value = read(raw, lower, pascal);
    return typeof value === "string" && value.length > 0 ? value : undefined;
};
const readBoolean = (raw, lower, pascal) => {
    const value = read(raw, lower, pascal);
    return typeof value === "boolean" ? value : false;
};
const normalizeUploadResponse = (raw) => ({
    success: readBoolean(raw, "success", "Success"),
    message: readString(raw, "message", "Message"),
    id: readString(raw, "id", "Id"),
    requiresReplaceConfirmation: readBoolean(raw, "requiresReplaceConfirmation", "RequiresReplaceConfirmation"),
    replaced: readBoolean(raw, "replaced", "Replaced"),
    existingId: readString(raw, "existingId", "ExistingId"),
    existingName: readString(raw, "existingName", "ExistingName"),
});
async function confirmReplace({ editContext, fileName, mediaName, directUpdate, }) {
    const message = directUpdate
        ? `Update "${mediaName}" with "${fileName}"? The media item ID and existing references will stay the same.`
        : `A media item named "${mediaName}" already exists. Replace it with "${fileName}"? The media item ID and existing references will stay the same.`;
    if (!editContext?.confirm) {
        return typeof window !== "undefined" ? window.confirm(message) : false;
    }
    return await new Promise((resolve) => {
        editContext.confirm({
            header: directUpdate ? "Update media item?" : "Replace media item?",
            message,
            acceptLabel: directUpdate ? "Update" : "Replace",
            rejectLabel: "Cancel",
            accept: () => resolve(true),
            reject: () => resolve(false),
        });
    });
}
async function postMediaFile({ file, folderId, replaceItemId, replace, }) {
    const params = new URLSearchParams();
    if (folderId)
        params.set("folder", folderId);
    if (replaceItemId)
        params.set("replaceItemId", replaceItemId);
    if (replace)
        params.set("replace", "true");
    const formData = new FormData();
    formData.append("file", file);
    const query = params.toString();
    const response = await fetch(`/parhelia/upload${query ? `?${query}` : ""}`, {
        method: "POST",
        body: formData,
    });
    const body = await response.text();
    let raw = {};
    if (body) {
        try {
            raw = JSON.parse(body);
        }
        catch {
            raw = { Message: body };
        }
    }
    if (!response.ok) {
        throw new Error(normalizeUploadResponse(raw).message ||
            response.statusText ||
            "Upload failed");
    }
    return normalizeUploadResponse(raw);
}
async function refreshMediaItem(editContext, mediaItemId, language = "en", itemDescriptor, refreshFields) {
    if (!editContext || !mediaItemId)
        return;
    await editContext.itemsRepository.refreshItems([
        itemDescriptor ?? {
            id: mediaItemId,
            language,
            version: 0,
            database: "master",
        },
    ], {
        properties: true,
        ...(refreshFields?.length ? { fields: refreshFields } : {}),
    });
    editContext.requestRefresh("immediate");
}
export async function uploadMediaFiles({ files, folderId, editContext, language, }) {
    const uploaded = [];
    for (const file of files) {
        try {
            let result = await postMediaFile({ file, folderId });
            if (result.requiresReplaceConfirmation && result.existingId) {
                const accepted = await confirmReplace({
                    editContext,
                    fileName: file.name,
                    mediaName: result.existingName || file.name,
                });
                if (!accepted)
                    continue;
                result = await postMediaFile({
                    file,
                    folderId,
                    replace: true,
                });
            }
            if (!result.success) {
                toast.error(result.message || `Failed to upload ${file.name}.`);
                continue;
            }
            if (result.replaced) {
                toast.success("Media item updated.");
            }
            await refreshMediaItem(editContext, result.id, language);
            uploaded.push(result);
        }
        catch (error) {
            console.error("Error uploading media file:", error);
            toast.error(error instanceof Error
                ? error.message
                : `Failed to upload ${file.name}.`);
        }
    }
    return uploaded;
}
export async function replaceMediaItemWithFile({ file, mediaItem, editContext, language, itemDescriptor, refreshFields, skipConfirmation, }) {
    const accepted = skipConfirmation ||
        (await confirmReplace({
            editContext,
            fileName: file.name,
            mediaName: mediaItem.name,
            directUpdate: true,
        }));
    if (!accepted)
        return undefined;
    try {
        const result = await postMediaFile({
            file,
            replaceItemId: mediaItem.id,
        });
        if (!result.success) {
            toast.error(result.message || `Failed to update ${mediaItem.name}.`);
            return undefined;
        }
        toast.success("Media item updated.");
        await refreshMediaItem(editContext, result.id || mediaItem.id, language, itemDescriptor, refreshFields);
        return result;
    }
    catch (error) {
        console.error("Error updating media item:", error);
        toast.error(error instanceof Error
            ? error.message
            : `Failed to update ${mediaItem.name}.`);
        return undefined;
    }
}
//# sourceMappingURL=mediaUpload.js.map