/**
 * List Users Endpoint
 * GET /v1/users
 *
 * Returns paginated list of users
 *
 * Query params:
 * - page: page number (default: 1)
 * - limit: records per page (default: 10, max: 100)
 * - search: search by name or email
 * - status: filter by status (active, inactive)
 */

const axios = require('axios');

module.exports = async (req, res, next, slmapi) => {
    try {
        // Parámetros de paginación
        const page = Math.max(1, parseInt(req.query.page) || 1);
        const limit = Math.min(100, Math.max(1, parseInt(req.query.limit) || 10));
        const from = (page - 1) * limit;

        // Búsqueda
        const search = req.query.search || null;
        const status = req.query.status || null;

        // Construir query de Elasticsearch
        const esQuery = {
            bool: {
                must: [
                    { term: { "slm.type.keyword": "user" } }
                ]
            }
        };

        // Filtro por estado
        if (status) {
            esQuery.bool.must.push({ term: { "status.keyword": status } });
        }

        // Búsqueda por nombre o email
        if (search) {
            esQuery.bool.must.push({
                multi_match: {
                    query: search,
                    fields: ["name", "lastname", "email"],
                    type: "phrase_prefix"
                }
            });
        }

        // Obtener total de registros (count)
        const countQuery = `${slmapi.es_server}/${slmapi.es_index}/_count`;
        const countRequest = await axios.post(countQuery, {
            query: esQuery
        });
        const total = countRequest.data.count;

        // Obtener usuarios
        const searchQuery = `${slmapi.es_server}/${slmapi.es_index}/_search`;
        const searchRequest = await axios.post(searchQuery, {
            query: esQuery,
            from: from,
            size: limit,
            sort: [
                { "slm.timestamp": { order: "desc" } }
            ],
            _source: [
                "name", "lastname", "email", "status",
                "profile", "slm.timestamp"
            ]
        });

        // Formatear respuesta
        const usersList = searchRequest.data.hits.hits.map(hit => ({
            id: hit._id,
            name: hit._source.name || '',
            lastname: hit._source.lastname || '',
            email: hit._source.email,
            status: hit._source.status || 'active',
            profile: hit._source.profile || null,
            created_at: hit._source.slm?.timestamp || null
        }));

        return res.status(200).json({
            error: false,
            data: {
                users: usersList,
                pagination: {
                    page: page,
                    limit: limit,
                    total: total,
                    pages: Math.ceil(total / limit)
                }
            },
            timestamp: slmapi.timestamp()
        });

    } catch (error) {
        console.error('Error listing users:', error.message);
        return res.status(500).json({
            error: true,
            message: 'Error retrieving users',
            timestamp: slmapi.timestamp()
        });
    }
};
