/**
 * Login Endpoint
 * POST /v1/auth/login
 *
 * Authenticates a user and returns session token
 *
 * Body:
 * {
 *   "email": "user@example.com",
 *   "password": "password123"
 * }
 */

const axios = require('axios');

module.exports = async (req, res, next, slmapi) => {
    const { email, password } = req.body;

    // Validar campos requeridos
    if (!email || !password) {
        return res.status(400).json({
            error: true,
            message: 'Email and password are required',
            timestamp: slmapi.timestamp()
        });
    }

    try {
        // Buscar usuario por email en Elasticsearch
        const query = `${slmapi.es_server}/${slmapi.es_index}/_search`;
        const requestBody = {
            "query": {
                "bool": {
                    "must": [
                        { "term": { "slm.type.keyword": "user" } },
                        { "term": { "email.keyword": email } }
                    ]
                }
            }
        };

        const request = await axios.post(query, requestBody);

        if (request.data?.hits?.total?.value === 0) {
            return res.status(401).json({
                error: true,
                message: 'Invalid credentials',
                timestamp: slmapi.timestamp()
            });
        }

        const user = request.data.hits.hits[0]._source;
        const userId = request.data.hits.hits[0]._id;

        // Verificar contraseña
        const passwordMatch = await slmapi.bcrypt.compare(password, user.password);

        if (!passwordMatch) {
            return res.status(401).json({
                error: true,
                message: 'Invalid credentials',
                timestamp: slmapi.timestamp()
            });
        }

        // Verificar que el usuario esté activo
        if (user.status && user.status !== 'active') {
            return res.status(403).json({
                error: true,
                message: 'User account is not active',
                timestamp: slmapi.timestamp()
            });
        }

        // Generar token de sesión (simplificado)
        const crypto = require('crypto');
        const token = crypto.randomBytes(32).toString('hex');

        // Actualizar última sesión del usuario
        const updateQuery = `${slmapi.es_server}/${slmapi.es_index}/_update/${userId}`;
        await axios.post(updateQuery, {
            doc: {
                last_login: slmapi.timestamp(),
                last_login_ip: req.ip || req.connection.remoteAddress
            }
        });

        // Respuesta exitosa
        return res.status(200).json({
            error: false,
            message: 'Login successful',
            data: {
                token: token,
                user: {
                    id: userId,
                    name: user.name || '',
                    lastname: user.lastname || '',
                    email: user.email,
                    profile: user.profile || null
                },
                expires_in: 3600 // 1 hora
            },
            timestamp: slmapi.timestamp()
        });

    } catch (error) {
        console.error('Login error:', error.message);
        return res.status(500).json({
            error: true,
            message: 'Error processing login',
            timestamp: slmapi.timestamp()
        });
    }
};
