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 videos = await dbSAPPS.Video.findAll({
            where: filterConditions,
            order: [['modified', 'DESC']],
            include: [{
                model: dbSAPPS.User,
                as: 'user',
                attributes: ['email']
            }]
        });

        return {
            videos,
            success: true,
            message: 'Videos has been loaded!'
        };
    } catch (error) {
        const errorMessage = error.message || 'Failed to load videos!';
        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 videos = await dbSAPPS.Video.findAll({
            where: filterConditions,
            order: [['modified', 'DESC']],
            include: [{
                model: dbSAPPS.User,
                as: 'user',
                attributes: ['email']
            }]
        });

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

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

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

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

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

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

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

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

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

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

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

            }
        }

        if (params.display_name && params.display_name !== video.display_name) {
            const existingDisplayName = await dbSAPPS.Video.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 video.update(params);
        return {
            success: true,
            message: 'Video has been updated!'
        };
    } catch (error) {
        const errorMessage = error.message || 'Failed to update video.';
        return {
            success: false,
            message: errorMessage
        };
    }
}

async function enabled(id, params) {
    try {
        const video = await dbSAPPS.Video.findByPk(id);
        if (!video) return {
            success: false,
            message: 'Video 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 video.update(updateData);
        return {
            success: true,
            message: 'Video has been updated!'
        };
    } catch (error) {
        const errorMessage = error.message || 'Failed to update video.';
        return {
            success: false,
            message: errorMessage
        };
    }
}

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

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