
import { McpServer, ResourceTemplate } from '@modelcontextprotocol/sdk/server/mcp.js';
import { Logger } from '../../utils/logger.js';
import { AtlassianConfig, getJiraV2Client } from '../../utils/atlassian-api-base.js';
import { userSchema } from '../../schemas/jira.js';
import { Config, Resources } from '../../utils/mcp-helpers.js';

const logger = Logger.getLogger('JiraResource:Myself');

/**
 * Helper function to get current user details from Jira
 */
async function getMyself(config: AtlassianConfig): Promise<any> {
    try {
        const jiraClient = getJiraV2Client(config);
        return await jiraClient.myself.getCurrentUser();
    } catch (error) {
        logger.error(`Error getting Jira current user:`, error);
        throw error;
    }
}

/**
 * Register Jira myself resource
 * @param server MCP Server instance
 */
export function registerMyselfResource(server: McpServer) {
    logger.info('Registering Jira myself resource...');

    server.resource(
        'jira-myself',
        new ResourceTemplate('jira://myself', {
            list: async (_extra) => ({
                resources: [
                    {
                        uri: 'jira://myself',
                        name: 'Jira Current User',
                        description: 'Get details of the currently authenticated Jira user',
                        mimeType: 'application/json'
                    }
                ]
            })
        }),
        async (uri, _params, _extra) => {
            try {
                const config = Config.getAtlassianConfigFromEnv();
                logger.info(`Getting details for current Jira user`);
                const user = await getMyself(config);

                // Format returned data matches userSchema
                const formattedUser = {
                    accountId: user.accountId,
                    displayName: user.displayName,
                    emailAddress: user.emailAddress,
                    active: user.active,
                    avatarUrl: user.avatarUrls?.['48x48'] || '',
                    timeZone: user.timeZone,
                    locale: user.locale
                };

                const uriString = typeof uri === 'string' ? uri : uri.href;
                return Resources.createStandardResource(
                    uriString,
                    [formattedUser],
                    'user',
                    userSchema,
                    1,
                    1,
                    0,
                    user.self || ''
                );
            } catch (error) {
                logger.error(`Error getting current user details:`, error);
                throw error;
            }
        }
    );

    logger.info('Jira myself resource registered successfully');
}
