"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.apiRequest = apiRequest;
exports.pollTaskResult = pollTaskResult;
const n8n_workflow_1 = require("n8n-workflow");
const TERMINAL_STATUSES = ['SUCCEEDED', 'FAILED', 'CANCELED'];
const DEFAULT_POLL_INTERVAL_MS = 15_000;
const MAX_POLL_ATTEMPTS = 60;
async function apiRequest(method, endpoint, parameters) {
    const { body, qs, option } = parameters ?? {};
    const credentials = await this.getCredentials('alibabaCloudApi');
    const uri = `${credentials.url}${endpoint}`;
    const headers = parameters?.headers ?? {};
    const options = {
        headers,
        method,
        body,
        qs,
        url: uri,
        json: true,
    };
    if (option && Object.keys(option).length !== 0) {
        Object.assign(options, option);
    }
    const response = await this.helpers.httpRequestWithAuthentication.call(this, 'alibabaCloudApi', options);
    if (response && response.error === null) {
        delete response.error;
    }
    return response;
}
async function pollTaskResult(taskId, pollIntervalMs = DEFAULT_POLL_INTERVAL_MS) {
    for (let attempt = 0; attempt < MAX_POLL_ATTEMPTS; attempt++) {
        const response = await apiRequest.call(this, 'GET', `/api/v1/tasks/${taskId}`);
        const taskStatus = response?.output?.task_status;
        if (TERMINAL_STATUSES.includes(taskStatus)) {
            if (taskStatus === 'FAILED') {
                const errorCode = response?.output?.code || response?.code || 'UNKNOWN';
                const errorMessage = response?.output?.message || response?.message || 'Video generation task failed';
                throw new n8n_workflow_1.NodeOperationError(this.getNode(), `Task failed: [${errorCode}] ${errorMessage}`);
            }
            if (taskStatus === 'CANCELED') {
                throw new n8n_workflow_1.NodeOperationError(this.getNode(), 'Video generation task was canceled');
            }
            return response;
        }
        await (0, n8n_workflow_1.sleep)(pollIntervalMs);
    }
    throw new n8n_workflow_1.NodeOperationError(this.getNode(), `Task ${taskId} did not complete within the maximum polling time. Last status was not terminal. You can query the task manually using the task ID.`);
}
//# sourceMappingURL=index.js.map