
import { z } from 'zod';
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
import { searchIssues } from '../../utils/jira-resource-api-v2.js';

export function registerSearchIssuesTool(server: McpServer) {
    server.tool(
        'searchIssues',
        'Search for Jira issues using JQL (Jira Query Language). Use "currentUser()" to refer to the currently authenticated user.',
        {
            jql: z.string().describe('The JQL query string. Example: "assignee = currentUser() AND status = Open"'),
            maxResults: z.number().optional().describe('Maximum number of results to return (default: 50)'),
            fields: z.array(z.string()).optional().describe('List of fields to return for each issue')
        },
        async ({ jql, maxResults }, context) => {
            const config = (context as any).atlassianConfig;
            const results = await searchIssues(config, jql, maxResults);

            const issues = results.issues.map((issue: any) => ({
                key: issue.key,
                id: issue.id,
                summary: issue.fields.summary,
                status: issue.fields.status?.name,
                assignee: issue.fields.assignee?.displayName,
                priority: issue.fields.priority?.name,
                type: issue.fields.issuetype?.name
            }));

            return {
                content: [{
                    type: 'text',
                    text: JSON.stringify({
                        total: results.total,
                        issues
                    }, null, 2)
                }]
            };
        }
    );
}
