"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.registerUserTools = registerUserTools;
const userService = __importStar(require("../../../services/user"));
const roleService = __importStar(require("../../../services/role"));
const schemas_1 = require("./schemas");
function registerUserTools(server) {
    // mirrors GET /api/users
    server.registerTool('list_users', {
        title: 'List Users',
        description: 'List user accounts with optional role and status filters.',
        inputSchema: schemas_1.listUsersSchema,
    }, async (args) => {
        const { users, total } = await userService.listUsers({
            role: args.role,
            status: args.status,
            limit: args.limit,
            offset: args.offset,
        });
        return {
            content: [{
                    type: 'text',
                    text: JSON.stringify({
                        total,
                        count: users.length,
                        users: users.map((u) => ({
                            id: u.id,
                            external_id: u.external_id,
                            display_name: u.display_name,
                            account_type: u.account_type,
                            status: u.status,
                        })),
                    }),
                }],
        };
    });
    // mirrors POST /api/users
    server.registerTool('create_user', {
        title: 'Create User',
        description: 'Create a new user account with optional roles. The user can then ' +
            'claim and resolve escalations for their assigned roles.',
        inputSchema: schemas_1.createUserSchema,
    }, async (args) => {
        const user = await userService.createUser({
            external_id: args.external_id,
            display_name: args.display_name,
            email: args.email,
            roles: args.roles,
        });
        return {
            content: [{ type: 'text', text: JSON.stringify(user) }],
        };
    });
    // mirrors POST /api/users/:id/roles
    server.registerTool('add_user_role', {
        title: 'Add User Role',
        description: 'Assign a role to a user. Role type: member, admin, or superadmin.',
        inputSchema: schemas_1.addUserRoleSchema,
    }, async (args) => {
        const result = await userService.addUserRole(args.user_id, args.role, args.type);
        return {
            content: [{ type: 'text', text: JSON.stringify(result) }],
        };
    });
    // mirrors DELETE /api/users/:id/roles/:role
    server.registerTool('remove_user_role', {
        title: 'Remove User Role',
        description: 'Remove a role from a user.',
        inputSchema: schemas_1.removeUserRoleSchema,
    }, async (args) => {
        const removed = await userService.removeUserRole(args.user_id, args.role);
        if (!removed) {
            return {
                content: [{ type: 'text', text: JSON.stringify({ error: 'Role not found' }) }],
                isError: true,
            };
        }
        return {
            content: [{ type: 'text', text: JSON.stringify({ removed: true }) }],
        };
    });
    // mirrors GET /api/roles
    server.registerTool('list_roles', {
        title: 'List Roles',
        description: 'List all distinct roles known to the system.',
        inputSchema: schemas_1.listRolesSchema,
    }, async (_args) => {
        const roles = await roleService.listDistinctRoles();
        return {
            content: [{ type: 'text', text: JSON.stringify({ roles }) }],
        };
    });
    // mirrors POST /api/roles
    server.registerTool('create_role', {
        title: 'Create Role',
        description: 'Create a new role. Role names must be lowercase alphanumeric ' +
            'with hyphens/underscores, starting with a letter.',
        inputSchema: schemas_1.createRoleSchema,
    }, async (args) => {
        const trimmed = args.role.trim().toLowerCase();
        if (!/^[a-z][a-z0-9_-]*$/.test(trimmed)) {
            return {
                content: [{
                        type: 'text',
                        text: JSON.stringify({ error: 'Role must start with a letter and contain only lowercase letters, numbers, hyphens, and underscores' }),
                    }],
                isError: true,
            };
        }
        await roleService.createRole(trimmed);
        return {
            content: [{ type: 'text', text: JSON.stringify({ role: trimmed, created: true }) }],
        };
    });
    // mirrors POST /api/roles/escalation-chains
    server.registerTool('add_escalation_chain', {
        title: 'Add Escalation Chain',
        description: 'Define an escalation path from one role to another. Users with ' +
            'the source role can escalate work to the target role.',
        inputSchema: schemas_1.addEscalationChainSchema,
    }, async (args) => {
        await roleService.addEscalationChain(args.source_role, args.target_role);
        return {
            content: [{
                    type: 'text',
                    text: JSON.stringify({
                        created: true,
                        source_role: args.source_role,
                        target_role: args.target_role,
                    }),
                }],
        };
    });
}
