
import { z } from 'zod';
import { AtlassianConfig } from '../../utils/atlassian-api-base.js';
import { addComment } from '../../utils/jira-tool-api-v2.js';
import { ApiError } from '../../utils/error-handler.js';
import { Logger } from '../../utils/logger.js';
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
import { Tools, Config } from '../../utils/mcp-helpers.js';

// Initialize logger
const logger = Logger.getLogger('JiraTools:addComment');

// Input parameter schema
export const addCommentSchema = z.object({
    issueIdOrKey: z.string().describe('ID or key of the issue (e.g., PROJ-123)'),
    comment: z.string().describe('The comment text')
});

type AddCommentParams = z.infer<typeof addCommentSchema>;

async function addCommentToolImpl(params: AddCommentParams, context: any) {
    const config: AtlassianConfig = Config.getConfigFromContextOrEnv(context);
    logger.info(`Adding comment to issue ${params.issueIdOrKey}`);
    const result = await addComment(
        config,
        params.issueIdOrKey,
        params.comment
    );
    return {
        issueIdOrKey: params.issueIdOrKey,
        id: result.id,
        success: true,
        message: `Comment added to ${params.issueIdOrKey}`
    };
}

// Register the tool with MCP Server
export const registerAddCommentTool = (server: McpServer) => {
    server.tool(
        'addComment',
        'Add a new comment to a Jira issue',
        addCommentSchema.shape,
        async (params: AddCommentParams, context: Record<string, any>) => {
            try {
                const result = await addCommentToolImpl(params, context);
                return {
                    content: [
                        {
                            type: 'text',
                            text: JSON.stringify(result)
                        }
                    ]
                };
            } catch (error) {
                return {
                    content: [
                        {
                            type: 'text',
                            text: JSON.stringify({ success: false, error: error instanceof Error ? error.message : String(error) })
                        }
                    ],
                    isError: true
                };
            }
        }
    );
};
