"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.apiEndpoints = void 0;
const guards_1 = require("../guards");
const state_stream_1 = require("../state-stream");
const mapEndpoint = (step) => {
    return {
        id: step.filePath,
        method: step.config.method,
        path: step.config.path,
        description: step.config.description,
        queryParams: step.config.queryParams,
        responseSchema: step.config.responseSchema,
        bodySchema: step.config.bodySchema,
    };
};
class ApiEndpointsStream extends state_stream_1.StateStream {
    constructor(lockedData) {
        super();
        this.lockedData = lockedData;
    }
    async get(id) {
        const endpoint = this.lockedData.apiSteps().find((step) => step.config.path === id);
        return endpoint ? mapEndpoint(endpoint) : null;
    }
    async update(_, data) {
        return data;
    }
    async delete(id) {
        return { id };
    }
    async create(_, data) {
        return data;
    }
    async getList() {
        return this.lockedData.apiSteps().map(mapEndpoint);
    }
    getGroupId() {
        /**
         * We're making it static to default because we only have one group of api endpoints
         *
         * In the future, we might want to have group of endpoints by Flows
         */
        return 'default';
    }
}
const apiEndpoints = (lockedData) => {
    const stream = lockedData.createStream({
        filePath: '__motia.api-endpoints.ts',
        hidden: true,
        config: {
            name: '__motia.api-endpoints',
            baseConfig: { storageType: 'custom', factory: () => new ApiEndpointsStream(lockedData) },
            schema: null,
        },
    })();
    const apiStepCreated = (step) => {
        if ((0, guards_1.isApiStep)(step)) {
            stream.create(step.filePath, {
                id: step.filePath,
                method: step.config.method,
                path: step.config.path,
                description: step.config.description,
                queryParams: step.config.queryParams,
            });
        }
    };
    const apiStepUpdated = (step) => {
        if ((0, guards_1.isApiStep)(step)) {
            stream.update(step.filePath, mapEndpoint(step));
        }
    };
    const apiStepRemoved = (step) => {
        if ((0, guards_1.isApiStep)(step)) {
            stream.delete(step.filePath);
        }
    };
    lockedData.onStep('step-created', apiStepCreated);
    lockedData.onStep('step-updated', apiStepUpdated);
    lockedData.onStep('step-removed', apiStepRemoved);
};
exports.apiEndpoints = apiEndpoints;
