import { logger } from "../util/logger.js";
/**
 * Initiates an export of a Cloudflare D1 database and returns a download URL.
 * Implements recursive polling with bookmark handling, similar to wrangler.
 * Waits indefinitely until the export process completes or fails.
 *
 * Based on Cloudflare API:
 * https://developers.cloudflare.com/api/resources/d1/subresources/database/methods/export/
 * and wrangler implementation.
 *
 * @param options Options including the database ID and optional dump parameters.
 * @returns An object containing the download URL, filename, and status upon completion.
 * @throws Will throw an error if the API call fails or the export process reports an error.
 */
export async function exportD1Database(api, options, currentBookmark) {
    const response = await api.post(`/accounts/${api.accountId}/d1/database/${options.databaseId}/export`, {
        output_format: "polling",
        dump_options: options.dumpOptions || {},
        current_bookmark: currentBookmark,
    });
    if (!response.ok) {
        const errorData = (await response.json());
        throw new Error(`Failed to export D1 database: ${errorData.error || errorData.errors?.[0]?.message || "Unknown error"}`);
    }
    const { result: data } = (await response.json());
    if (!data.success) {
        throw new Error(data.error || "Unknown error during D1 export");
    }
    // Log messages for visibility
    if (data.messages && data.messages.length > 0) {
        for (const message of data.messages) {
            logger.log(`D1 Export: ${message}`);
        }
    }
    if (data.status === "complete" && data.result) {
        return {
            filename: data.result.filename,
            signed_url: data.result.signed_url,
            status: data.status,
            success: data.success,
        };
    }
    else if (data.status === "error") {
        throw new Error(data.error || "Error during D1 export");
    }
    else {
        // Continue polling with bookmark
        return exportD1Database(api, options, data.at_bookmark);
    }
}
//# sourceMappingURL=d1-export.js.map