"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.createSearchWorkflowsTool = void 0;
exports.searchWorkflows = searchWorkflows;
const zod_1 = __importDefault(require("zod"));
const mcp_constants_1 = require("../mcp.constants");
const schemas_1 = require("./schemas");
const MAX_RESULTS = 200;
const inputSchema = {
    limit: (0, schemas_1.createLimitSchema)(MAX_RESULTS),
    query: zod_1.default.string().optional().describe('Filter by name or description'),
    projectId: zod_1.default.string().optional(),
};
const outputSchema = {
    data: zod_1.default
        .array(zod_1.default.object({
        id: zod_1.default.string().describe('The unique identifier of the workflow'),
        name: zod_1.default.string().nullable().describe('The name of the workflow'),
        description: zod_1.default.string().nullable().optional().describe('The description of the workflow'),
        active: zod_1.default.boolean().nullable().describe('Whether the workflow is active'),
        createdAt: zod_1.default
            .string()
            .nullable()
            .describe('The ISO timestamp when the workflow was created'),
        updatedAt: zod_1.default
            .string()
            .nullable()
            .describe('The ISO timestamp when the workflow was last updated'),
        triggerCount: zod_1.default
            .number()
            .nullable()
            .describe('The number of triggers associated with the workflow'),
        scopes: zod_1.default.array(zod_1.default.string()).describe('User permissions for this workflow'),
        canExecute: zod_1.default
            .boolean()
            .describe('Whether the user has permission to execute this workflow'),
        availableInMCP: zod_1.default.boolean().describe('Whether the workflow is visible to MCP tools'),
    }))
        .describe('List of workflows matching the query'),
    count: zod_1.default.number().int().min(0).describe('Total number of workflows that match the filters'),
};
const createSearchWorkflowsTool = (user, workflowService, telemetry) => {
    return {
        name: 'search_workflows',
        config: {
            description: 'Search for workflows with optional filters. Returns a preview of each workflow.',
            inputSchema,
            outputSchema,
            annotations: {
                title: 'Search Workflows',
                readOnlyHint: true,
                destructiveHint: false,
                idempotentHint: true,
                openWorldHint: false,
            },
        },
        handler: async ({ limit = MAX_RESULTS, query, projectId, }) => {
            const parameters = { limit, query, projectId };
            const telemetryPayload = {
                user_id: user.id,
                tool_name: 'search_workflows',
                parameters,
            };
            try {
                const payload = await searchWorkflows(user, workflowService, {
                    limit,
                    query,
                    projectId,
                });
                telemetryPayload.results = {
                    success: true,
                    data: {
                        count: payload.count,
                    },
                };
                telemetry.track(mcp_constants_1.USER_CALLED_MCP_TOOL_EVENT, telemetryPayload);
                return {
                    structuredContent: payload,
                    content: [
                        {
                            type: 'text',
                            text: JSON.stringify(payload),
                        },
                    ],
                };
            }
            catch (error) {
                telemetryPayload.results = {
                    success: false,
                    error: error instanceof Error ? error.message : String(error),
                };
                telemetry.track(mcp_constants_1.USER_CALLED_MCP_TOOL_EVENT, telemetryPayload);
                throw error;
            }
        },
    };
};
exports.createSearchWorkflowsTool = createSearchWorkflowsTool;
async function searchWorkflows(user, workflowService, { limit = MAX_RESULTS, query, projectId }) {
    const safeLimit = Math.min(Math.max(1, limit), MAX_RESULTS);
    const options = {
        take: safeLimit,
        filter: {
            isArchived: false,
            ...(query ? { query } : {}),
            ...(projectId ? { projectId } : {}),
        },
        select: {
            id: true,
            activeVersionId: true,
            name: true,
            description: true,
            createdAt: true,
            updatedAt: true,
            triggerCount: true,
            ownedBy: true,
            settings: true,
        },
    };
    const { workflows, count } = await workflowService.getMany(user, options, true, false, false);
    const formattedWorkflows = workflows.map((workflow) => {
        const { id, name, description, activeVersionId, createdAt, updatedAt, triggerCount, settings } = workflow;
        const scopes = ('scopes' in workflow ? workflow.scopes : undefined) ?? [];
        return {
            id,
            name,
            description,
            active: activeVersionId !== null,
            createdAt: createdAt.toISOString(),
            updatedAt: updatedAt.toISOString(),
            triggerCount,
            scopes,
            canExecute: scopes.includes('workflow:execute'),
            availableInMCP: settings?.availableInMCP ?? false,
        };
    });
    return { data: formattedWorkflows, count };
}
//# sourceMappingURL=search-workflows.tool.js.map