const dbSAPPS = require('../../helpers/db');
require('dotenv').config();
const { Op } = require('sequelize');

module.exports = {
    create,
    getAll,
    filter,
    count,
    update,
    delete: _delete
};

async function getAll() {
    try {
        const userActivities = await dbSAPPS.UserActivity.findAll({
            order: [['createdAt', 'DESC']],
            include: [
                {
                    model: dbSAPPS.User,
                    as: 'user',
                    attributes: ['id', 'full_name']
                }
            ]
        });
        
        return {
            userActivities,
            success: true,
            message: 'Activities user has been loaded!'
        };
    } catch (error) {
        const errorMessage = error.message || 'Failed to load activities user!';
        return {
            success: false,
            message: errorMessage
        };
    }
}

async function filter(params) {
    const filterConditions = {};

    if (params.user_id) {
        filterConditions.user_id = {
            [Op.like]: `%${params.user_id}%`,
        };
    }

    const startDate = params.start_date ? new Date(params.start_date) : null;
    const endDate = params.end_date ? new Date(params.end_date) : null;

    if (startDate || endDate) {
        filterConditions.createdAt = {};
        if (startDate) {
            filterConditions.createdAt[Op.gte] = startDate;
        }
        if (endDate) {
            filterConditions.createdAt[Op.lte] = endDate;
        }
    }

    try {
        const userActivities = await dbSAPPS.UserActivity.findAll({
            where: filterConditions,
            order: [['createdAt', 'ASC']],
            include: [
                {
                    model: dbSAPPS.User,
                    as: 'user',
                    attributes: ['id', 'full_name']
                }
            ]
        });

        return {
            userActivities,
            success: true,
            message: "Activities user has been loaded!"
        };
    } catch (error) {
        console.error('Error retrieving activities user: ', error);
        const errorMessage = error.message || 'Failed to retrieve activities user. Please try again later.';
        return {
            success: false,
            message: errorMessage
        };
    }
}

async function count() {
    try {
        const count = await dbSAPPS.UserActivity.count({
            where: { enabled: true }
        });

        return {
            success: true,
            count,
            message: "Activities user has been loaded!"
        };
    } catch (error) {
        console.error('Error counting activities user: ', error);
        return {
            success: false,
            message: 'Failed to retrieve count activities user. Please try again later.'
        };
    }
}

async function create(params) {
    try {
        const newUserActivity = await dbSAPPS.UserActivity.create(params);
        return {
            success: true,
            message: 'Activities user has been created!',
            userActivity: newUserActivity
        };
    } catch (error) {
        const errorMessage = error.message || 'An error occurred during creating activities user.';
        return {
            success: false,
            message: errorMessage
        };
    }
}

async function update(id, params) {
    try {
        const userActivity = await dbSAPPS.UserActivity.findByPk(id);
        if (!userActivity) return {
            success: false,
            message: 'Activities user not found!'
        };

        await userActivity.update(params);
        return {
            success: true,
            message: 'Activities user has been updated!'
        };
    } catch (error) {
        const errorMessage = error.message || 'Failed to update activity user.';
        return {
            success: false,
            message: errorMessage
        };
    }
}

async function _delete(id) {
    try {
        const userActivity = await dbSAPPS.UserActivity.findByPk(id);
        if (!userActivity) return { success: false, message: 'Activities user not found!' };

        await userActivity.destroy();
        return {
            success: true,
            message: 'Activities user has been deleted!'
        };
    } catch (error) {
        const errorMessage = error.message || 'Failed to delete activities user.';
        return {
            success: false,
            message: errorMessage
        };
    }
}
