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

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

async function getAll(params) {
    try {
        const filterConditions = {};

        if (params?.projectsId) {
            filterConditions.project_id = {
                [Op.in]: params?.projectsId
            };
        }

        const images = await dbSAPPS.Image.findAll({
            where: filterConditions,
            order: [['modified', 'DESC']],
            include: [{
                model: dbSAPPS.User,
                as: 'user',
                attributes: ['email']
            }]
        });

        return {
            images,
            success: true,
            message: 'Images has been loaded!'
        };
    } catch (error) {
        const errorMessage = error.message || 'Failed to load images!';
        return {
            success: false,
            message: errorMessage
        };
    }
}

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

    if (params?.projectsId) {
        filterConditions.project_id = {
            [Op.in]: params?.projectsId
        };
    }

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

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

    if (params.project_id) {
        filterConditions.project_id = {
            [Op.eq]: params.project_id,
        };
    }

    if (params.enabled) {
        filterConditions.enabled = {
            [Op.eq]: params.enabled === "1" ? true : false,
        };
    }

    try {
        const images = await dbSAPPS.Image.findAll({
            where: filterConditions,
            order: [['modified', 'DESC']],
            include: [{
                model: dbSAPPS.User,
                as: 'user',
                attributes: ['email']
            }]
        });

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

async function option() {
    try {
        const images = await dbSAPPS.Image.findAll({
            attributes: ['id', 'name', 'display_name', 'filename'],
            where: { enabled: true },
            order: [['name', 'ASC']]
        });

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

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

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

async function create(params) {
    try {
        if (!params.name || !params.display_name) return { success: false, message: 'Image name, display name are required!' };

        const existingName = await dbSAPPS.Image.findOne({ where: { name: params.name } });
        if (existingName) return { success: false, message: `Image name "${params.name}" is already taken.` };

        const existingDisplayName = await dbSAPPS.Image.findOne({ where: { display_name: params.display_name } });
        if (existingDisplayName) return { success: false, message: `Display name "${params.display_name}" is already taken.` };

        await dbSAPPS.Image.create(params);
        return {
            success: true,
            message: 'Image has been created!'
        };
    } catch (error) {
        const errorMessage = error.message || 'An error occurred during creating image.';
        return {
            success: false,
            message: errorMessage
        };
    }
}

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

        if (params.name && params.name !== image.name) {
            const existingName = await dbSAPPS.Image.findOne({ where: { name: params.name } });
            if (existingName) {
                if (existingName.id != params.id) {
                    return {
                        success: false,
                        message: `Image name "${params.name}" is already taken. Try again!`
                    };
                }

            }
        }

        if (params.display_name && params.display_name !== image.display_name) {
            const existingDisplayName = await dbSAPPS.Image.findOne({ where: { display_name: params.display_name } });
            if (existingDisplayName) {
                if (existingDisplayName.id != params.id) {
                    return {
                        success: false,
                        message: `Display name "${params.display_name}" is already taken. Try again!`
                    };
                }
            }
        }

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

async function enabled(id, params) {
    try {
        const image = await dbSAPPS.Image.findByPk(id);
        if (!image) return {
            success: false,
            message: 'Image not found!'
        };

        const updateData = {};
        updateData.enabled = params.enabled;
        if (params.modified_by) updateData.modified_by = params.modified_by;
        if (params.modified) updateData.modified = params.modified;

        // debug
        // console.log('id', id);
        // console.log('params', params);
        // console.log('updateData', updateData)

        await image.update(updateData);
        return {
            success: true,
            message: 'Image has been updated!'
        };
    } catch (error) {
        const errorMessage = error.message || 'Failed to update image.';
        return {
            success: false,
            message: errorMessage
        };
    }
}

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

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