"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.validate = void 0;
const api_schema_builder_1 = require("api-schema-builder");
const _1 = require(".");
const debug_1 = require("../../debug");
const openApi_1 = require("./openApi");
const debug = (0, debug_1.createDebug)('signalk-server:api:resources:validate');
class ValidationError extends Error {
}
const API_SCHEMA = (0, api_schema_builder_1.buildSchemaSync)(openApi_1.resourcesApiDoc);
exports.validate = {
    resource: (type, id, method, 
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    value) => {
        debug.enabled &&
            debug(`Validating ${type} ${method} ${JSON.stringify(value)}`);
        const endpoint = API_SCHEMA[`${_1.RESOURCES_API_PATH}/${type}${id ? '/:id' : ''}`][method.toLowerCase()];
        if (!endpoint) {
            throw new Error(`Validation: endpoint for ${type} ${method} not found`);
        }
        const valid = endpoint.body.validate(value);
        if (valid) {
            return;
        }
        else {
            debug(endpoint.body.errors);
            throw new ValidationError(JSON.stringify(endpoint.body.errors));
        }
    },
    query: (type, id, method, 
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    value) => {
        debug.enabled &&
            debug(`*** Validating query params for ${type} ${method} ${JSON.stringify(value)}`);
        const endpoint = API_SCHEMA[`${_1.RESOURCES_API_PATH}/${type}${id ? '/:id' : ''}`][method.toLowerCase()];
        if (!endpoint) {
            throw new Error(`Validation: endpoint for ${type} ${method} not found`);
        }
        const valid = endpoint.parameters.validate({ query: value });
        if (valid) {
            return;
        }
        else {
            debug(endpoint.parameters.errors);
            throw new ValidationError(JSON.stringify(endpoint.parameters.errors));
        }
    },
    // returns true if id is a valid Signal K UUID
    uuid: (id) => {
        const uuid = RegExp('^[0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-4[0-9A-Fa-f]{3}-[89ABab][0-9A-Fa-f]{3}-[0-9A-Fa-f]{12}$');
        return uuid.test(id);
    },
    // returns true if id is a valid Signal K Chart resource id
    chartId: (id) => {
        const uuid = RegExp('(^[A-Za-z0-9_-]{8,}$)');
        return uuid.test(id);
    }
};
//# sourceMappingURL=validate.js.map