"use strict";
/** AgentForms API client — thin wrapper over /api/v2/. */
Object.defineProperty(exports, "__esModule", { value: true });
exports.AgentForms = exports.SubmissionsClient = exports.KeysClient = exports.FormsClient = exports.AgentFormsError = void 0;
// ---------------------------------------------------------------------------
// Error class
// ---------------------------------------------------------------------------
class AgentFormsError extends Error {
    statusCode;
    response;
    constructor(message, statusCode = 0, response = null) {
        super(message);
        this.name = 'AgentFormsError';
        this.statusCode = statusCode;
        this.response = response;
    }
}
exports.AgentFormsError = AgentFormsError;
/**
 * Make an HTTP request and parse the JSON response.
 * Throws AgentFormsError on status >= 400.
 */
async function request(internals, method, path, options) {
    const url = new URL(`${internals.baseURL}/${path.replace(/^\//, '')}`);
    if (options?.params) {
        for (const [key, value] of Object.entries(options.params)) {
            url.searchParams.append(key, String(value));
        }
    }
    const controller = new AbortController();
    const timer = setTimeout(() => controller.abort(), internals.timeout * 1000);
    try {
        const headers = {
            Authorization: `Bearer ${internals.apiKey}`,
            Accept: 'application/json',
        };
        const fetchOptions = {
            method,
            headers,
            signal: controller.signal,
        };
        if (options?.body) {
            headers['Content-Type'] = 'application/json';
            fetchOptions.body = JSON.stringify(options.body);
        }
        const resp = await fetch(url.toString(), fetchOptions);
        if (resp.status >= 400) {
            let message;
            let body;
            try {
                body = await resp.json();
                message = body.error ?? resp.statusText;
            }
            catch {
                body = await resp.text();
                message = body;
            }
            throw new AgentFormsError(message, resp.status, body);
        }
        if (resp.status === 204) {
            return {};
        }
        return resp.json();
    }
    finally {
        clearTimeout(timer);
    }
}
/**
 * Enrich a Form object with computed URL properties.
 */
function enrichForm(raw) {
    return {
        ...raw,
        public_url: `https://agentforms.io/f/${raw.token}`,
        share_url: `https://agentforms.io/${raw.token}`,
    };
}
/**
 * Enrich a list of Form objects.
 */
function enrichFormsResponse(raw) {
    return {
        ...raw,
        forms: (raw.forms ?? []).map(enrichForm),
    };
}
// ---------------------------------------------------------------------------
// FormsClient
// ---------------------------------------------------------------------------
class FormsClient {
    _c;
    constructor(client) {
        this._c = client;
    }
    /** List all forms. */
    async list(limit = 50, offset = 0) {
        const result = await request(this._c, 'GET', '/forms', {
            params: { limit, offset },
        });
        return enrichFormsResponse(result);
    }
    /**
     * Create a new form programmatically.
     *
     * @param name - Form display name
     * @param fields - List of field definitions
     * @param metadata - Optional JSON metadata attached to the form
     */
    async create(name, fields, metadata) {
        const body = { name, fields };
        if (metadata) {
            body.metadata = metadata;
        }
        const result = await request(this._c, 'POST', '/forms', { body });
        return enrichForm(result);
    }
    /**
     * Generate a form from natural language using AI.
     * Tier-gated (Starter+).
     *
     * @param prompt - Natural language description (e.g., "A survey for event feedback")
     * @param formName - Override the AI-generated form name
     */
    async generate(prompt, formName) {
        const body = { prompt };
        if (formName) {
            body.form_name = formName;
        }
        const result = await request(this._c, 'POST', '/forms/generate', { body });
        return enrichForm(result);
    }
    /** Get form details by token. */
    async get(token) {
        const result = await request(this._c, 'GET', `/forms/${token}`);
        return enrichForm(result);
    }
    /** Replace all fields on a form. */
    async updateFields(token, fields) {
        return request(this._c, 'PUT', `/forms/${token}/fields`, { body: { fields } });
    }
    /** Delete a form and all submissions. */
    async delete(token) {
        return request(this._c, 'DELETE', `/forms/${token}`);
    }
    /** Get public form config. */
    async config(token) {
        return request(this._c, 'GET', `/forms/${token}/config`);
    }
}
exports.FormsClient = FormsClient;
// ---------------------------------------------------------------------------
// KeysClient
// ---------------------------------------------------------------------------
class KeysClient {
    _c;
    constructor(client) {
        this._c = client;
    }
    /** List all API keys. */
    async list() {
        const result = (await request(this._c, 'GET', '/keys'));
        return result.keys ?? [];
    }
    /**
     * Create a new API key.
     *
     * @param name - Human-readable name
     * @param permissions - List of permissions (defaults to all if omitted)
     * @returns Key details including the full_key (returned once — store it securely)
     */
    async create(name, permissions) {
        const body = { name };
        if (permissions) {
            const permObj = {};
            for (const p of permissions) {
                permObj[p] = true;
            }
            body.permissions = permObj;
        }
        return request(this._c, 'POST', '/keys', {
            body,
        });
    }
    /** Revoke an API key. */
    async revoke(keyId) {
        return request(this._c, 'DELETE', `/keys/${keyId}`);
    }
}
exports.KeysClient = KeysClient;
// ---------------------------------------------------------------------------
// SubmissionsClient
// ---------------------------------------------------------------------------
class SubmissionsClient {
    _c;
    constructor(client) {
        this._c = client;
    }
    /** List submissions for a form. */
    async list(formToken, limit = 50, offset = 0) {
        return request(this._c, 'GET', `/forms/${formToken}/submissions`, { params: { limit, offset } });
    }
    /** Get a single submission. */
    async get(formToken, submissionId) {
        return request(this._c, 'GET', `/forms/${formToken}/submissions/${submissionId}`);
    }
}
exports.SubmissionsClient = SubmissionsClient;
// ---------------------------------------------------------------------------
// Main client
// ---------------------------------------------------------------------------
/**
 * Client for the AgentForms Agent API.
 *
 * @example
 * ```ts
 * import { AgentForms } from '@agentforms/sdk';
 *
 * const af = new AgentForms('afk_live_...');
 *
 * // Create a form
 * const form = await af.forms.create('Customer Feedback', [
 *   { name: 'rating', label: 'Rating', type: 'select', options: ['1','2','3','4','5'], required: true },
 *   { name: 'feedback', label: 'Feedback', type: 'textarea' },
 * ]);
 * console.log(form.share_url);
 * ```
 */
class AgentForms {
    apiKey;
    baseURL;
    timeout;
    forms;
    keys;
    submissions;
    /**
     * @param apiKey - Your AgentForms API key
     * @param baseURL - API base URL (default: https://agentforms.io/api/v2)
     * @param timeout - Request timeout in seconds (default: 30)
     */
    constructor(apiKey, baseURL = 'https://agentforms.io/api/v2', timeout = 30) {
        this.apiKey = apiKey;
        this.baseURL = baseURL;
        this.timeout = timeout;
        const internals = {
            apiKey,
            baseURL: baseURL.replace(/\/+$/, ''),
            timeout,
        };
        this.forms = new FormsClient(internals);
        this.keys = new KeysClient(internals);
        this.submissions = new SubmissionsClient(internals);
    }
}
exports.AgentForms = AgentForms;
//# sourceMappingURL=client.js.map