"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.getDocumentFieldValues = void 0;
const zod_1 = require("zod");
const extensions_core_1 = require("@awell-health/extensions-core");
const config_1 = require("./config");
const DOCUMO_API_BASE = 'https://api.documo.com';
const SettingsSchema = zod_1.z.object({
    apiKey: zod_1.z.string().min(1),
});
exports.getDocumentFieldValues = {
    key: 'getDocumentFieldValues',
    title: 'Get Document Field Values',
    description: 'Retrieve field values for a specific document in a Documo workspace.',
    category: extensions_core_1.Category.DOCUMENT_MANAGEMENT,
    fields: config_1.fields,
    dataPoints: config_1.dataPoints,
    previewable: true,
    onEvent: async ({ payload, onComplete, onError }) => {
        const { fields: { workspaceId, documentId }, settings: { apiKey }, } = (0, extensions_core_1.validate)({
            schema: zod_1.z.object({
                fields: config_1.FieldsSchema,
                settings: SettingsSchema,
            }),
            payload,
        });
        const url = `${DOCUMO_API_BASE}/ws/v2/workspaces/${encodeURIComponent(workspaceId)}/documents/${encodeURIComponent(documentId)}/field-values`;
        const response = await fetch(url, {
            method: 'GET',
            headers: {
                Authorization: apiKey,
                'Content-Type': 'application/json',
            },
        });
        if (!response.ok) {
            const errorBody = await response.text();
            await onError({
                events: [
                    {
                        date: new Date().toISOString(),
                        text: {
                            en: `Documo API error (${response.status}): ${errorBody}`,
                        },
                        error: {
                            category: 'SERVER_ERROR',
                            message: `Documo API returned ${response.status}: ${errorBody}`,
                        },
                    },
                ],
            });
            return;
        }
        const data = await response.json();
        await onComplete({
            data_points: {
                fieldValues: JSON.stringify(data),
            },
        });
    },
};
//# sourceMappingURL=getDocumentFieldValues.js.map