/**
 * Get User Endpoint
 * GET /v1/users/:id
 *
 * Returns specific user information
 */

const axios = require('axios');

module.exports = async (req, res, next, slmapi) => {
    const userId = req.params.id;

    if (!userId) {
        return res.status(400).json({
            error: true,
            message: 'User ID is required',
            timestamp: slmapi.timestamp()
        });
    }

    try {
        // Obtener usuario por ID
        const query = `${slmapi.es_server}/${slmapi.es_index}/_doc/${userId}`;
        const request = await axios.get(query);

        if (!request.data.found) {
            return res.status(404).json({
                error: true,
                message: 'User not found',
                timestamp: slmapi.timestamp()
            });
        }

        const user = request.data._source;

        // Verificar que sea un usuario
        if (user.slm?.type !== 'user') {
            return res.status(404).json({
                error: true,
                message: 'User not found',
                timestamp: slmapi.timestamp()
            });
        }

        // Formatear respuesta (remover campos sensibles)
        const userData = {
            id: userId,
            name: user.name || '',
            lastname: user.lastname || '',
            email: user.email,
            status: user.status || 'active',
            profile: user.profile || null,
            created_at: user.slm?.timestamp || null,
            last_login: user.last_login || null,
            last_login_ip: user.last_login_ip || null
        };

        // Si tiene perfil, obtener información del perfil
        if (user.profile) {
            try {
                const profileQuery = `${slmapi.es_server}/${slmapi.es_index}/_doc/${user.profile}`;
                const profileRequest = await axios.get(profileQuery);

                if (profileRequest.data.found) {
                    const profile = profileRequest.data._source;
                    userData.profile_info = {
                        id: user.profile,
                        name: profile.name || '',
                        description: profile.description || ''
                    };
                }
            } catch (profileError) {
                // Silencioso, no romper si no se puede obtener el perfil
                console.warn('Could not fetch profile:', profileError.message);
            }
        }

        return res.status(200).json({
            error: false,
            data: userData,
            timestamp: slmapi.timestamp()
        });

    } catch (error) {
        console.error('Error getting user:', error.message);

        // Si es 404 de ES, retornar usuario no encontrado
        if (error.response?.status === 404) {
            return res.status(404).json({
                error: true,
                message: 'User not found',
                timestamp: slmapi.timestamp()
            });
        }

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