
import { z } from 'zod';
import { AtlassianConfig } from '../../utils/atlassian-api-base.js';
import { addWorklog } 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:addWorklog');

// Input parameter schema
export const addWorklogSchema = z.object({
    issueIdOrKey: z.string().describe('ID or key of the issue'),
    timeSpent: z.string().describe('Time spent (e.g., "3h 30m")'),
    comment: z.string().optional().describe('Comment for the worklog'),
    started: z.string().optional().describe('Started time (ISO 8601, e.g., "2023-01-01T12:00:00.000+0000")')
});

type AddWorklogParams = z.infer<typeof addWorklogSchema>;

async function addWorklogToolImpl(params: AddWorklogParams, context: any) {
    const config: AtlassianConfig = Config.getConfigFromContextOrEnv(context);
    logger.info(`Adding worklog to issue ${params.issueIdOrKey}`);
    const result = await addWorklog(
        config,
        params.issueIdOrKey,
        params.timeSpent,
        params.comment,
        params.started
    );
    return {
        issueIdOrKey: params.issueIdOrKey,
        id: result.id,
        success: true,
        message: `Worklog added to ${params.issueIdOrKey}`
    };
}

// Register the tool with MCP Server
export const registerAddWorklogTool = (server: McpServer) => {
    server.tool(
        'addWorklog',
        'Log work for a Jira issue',
        addWorklogSchema.shape,
        async (params: AddWorklogParams, context: Record<string, any>) => {
            try {
                const result = await addWorklogToolImpl(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
                };
            }
        }
    );
};
