"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.apiRequest = apiRequest;
exports.pollVideoTask = pollVideoTask;
exports.getVideoDownloadUrl = getVideoDownloadUrl;
const n8n_workflow_1 = require("n8n-workflow");
async function apiRequest(method, endpoint, parameters) {
    const { body, qs, option, headers } = parameters ?? {};
    const credentials = await this.getCredentials('minimaxApi');
    const baseUrl = credentials.url ?? 'https://api.minimax.io/v1';
    const url = `${baseUrl}${endpoint}`;
    const options = {
        headers: headers ?? {},
        method,
        body,
        qs,
        url,
        json: true,
    };
    if (option && Object.keys(option).length !== 0) {
        Object.assign(options, option);
    }
    return await this.helpers.httpRequestWithAuthentication.call(this, 'minimaxApi', options);
}
const VIDEO_TERMINAL_STATUSES = ['Success', 'Fail'];
const DEFAULT_POLL_INTERVAL_MS = 15_000;
const MAX_POLL_ATTEMPTS = 60;
async function pollVideoTask(taskId, pollIntervalMs = DEFAULT_POLL_INTERVAL_MS) {
    for (let attempt = 0; attempt < MAX_POLL_ATTEMPTS; attempt++) {
        const response = await apiRequest.call(this, 'GET', '/query/video_generation', {
            qs: { task_id: taskId },
        });
        const status = response?.status;
        if (VIDEO_TERMINAL_STATUSES.includes(status)) {
            if (status === 'Fail') {
                const errorCode = response?.base_resp?.status_code || 'UNKNOWN';
                const errorMessage = response?.base_resp?.status_msg || 'Video generation task failed';
                throw new n8n_workflow_1.NodeOperationError(this.getNode(), `Task failed: [${errorCode}] ${errorMessage}`);
            }
            const fileId = response?.file_id;
            if (!fileId) {
                throw new n8n_workflow_1.NodeOperationError(this.getNode(), 'Video generation succeeded but no file_id was returned');
            }
            return { fileId, status };
        }
        await (0, n8n_workflow_1.sleep)(pollIntervalMs);
    }
    throw new n8n_workflow_1.NodeOperationError(this.getNode(), `Video task ${taskId} did not complete within the maximum polling time. You can query the task manually using the task ID.`);
}
async function getVideoDownloadUrl(fileId) {
    const response = await apiRequest.call(this, 'GET', '/files/retrieve', {
        qs: { file_id: fileId },
    });
    const downloadUrl = response?.file?.download_url;
    if (!downloadUrl) {
        throw new n8n_workflow_1.NodeOperationError(this.getNode(), `Failed to retrieve download URL for file ${fileId}`);
    }
    return downloadUrl;
}
//# sourceMappingURL=index.js.map