
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');



const Sequelize = db.Sequelize;
const Op = Sequelize.Op;

module.exports = class Platform_configDBApi {
    

    
    static async create(data, options) {
        const currentUser = (options && options.currentUser) || { id: null };
        const transaction = (options && options.transaction) || undefined;

        const platform_config = await db.platform_config.create(
            {
                id: data.id || undefined,
        
        platform_fee_percent: data.platform_fee_percent
        ||
        null
            ,
            
        auto_release_days: data.auto_release_days
        ||
        null
            ,
            
        max_revision_count: data.max_revision_count
        ||
        null
            ,
            
        min_review_length: data.min_review_length
        ||
        null
            ,
            
        new_user_verify_email: data.new_user_verify_email
        ||
        false
        
            ,
            
        tutor_two_factor_required: data.tutor_two_factor_required
        ||
        false
        
            ,
            
        maintenance_mode: data.maintenance_mode
        ||
        false
        
            ,
            
        maintenance_message: data.maintenance_message
        ||
        null
            ,
            
        announcement_banner_enabled: data.announcement_banner_enabled
        ||
        false
        
            ,
            
        announcement_banner_text: data.announcement_banner_text
        ||
        null
            ,
            
        jitsi_sdk_key: data.jitsi_sdk_key
        ||
        null
            ,
            
        jitsi_sdk_secret: data.jitsi_sdk_secret
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        

        

        

        return platform_config;
    }
    

    static async bulkImport(data, options) {
        const currentUser = (options && options.currentUser) || { id: null };
        const transaction = (options && options.transaction) || undefined;

        // Prepare data - wrapping individual data transformations in a map() method
        const platform_configData = data.map((item, index) => ({
                id: item.id || undefined,
                
                platform_fee_percent: item.platform_fee_percent
            ||
            null
            ,
            
                auto_release_days: item.auto_release_days
            ||
            null
            ,
            
                max_revision_count: item.max_revision_count
            ||
            null
            ,
            
                min_review_length: item.min_review_length
            ||
            null
            ,
            
                new_user_verify_email: item.new_user_verify_email
            ||
            false
        
            ,
            
                tutor_two_factor_required: item.tutor_two_factor_required
            ||
            false
        
            ,
            
                maintenance_mode: item.maintenance_mode
            ||
            false
        
            ,
            
                maintenance_message: item.maintenance_message
            ||
            null
            ,
            
                announcement_banner_enabled: item.announcement_banner_enabled
            ||
            false
        
            ,
            
                announcement_banner_text: item.announcement_banner_text
            ||
            null
            ,
            
                jitsi_sdk_key: item.jitsi_sdk_key
            ||
            null
            ,
            
                jitsi_sdk_secret: item.jitsi_sdk_secret
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

        // Bulk create items
        const platform_config = await db.platform_config.bulkCreate(platform_configData, { transaction });

        // For each item created, replace relation files
        

        return platform_config;
    }

    static async update(id, data,  options) {
        const currentUser = (options && options.currentUser) || {id: null};
        const transaction = (options && options.transaction) || undefined;
        

        const platform_config = await db.platform_config.findByPk(id, {}, {transaction});


        

        const updatePayload = {};
        
        if (data.platform_fee_percent !== undefined) updatePayload.platform_fee_percent = data.platform_fee_percent;
        
        
        if (data.auto_release_days !== undefined) updatePayload.auto_release_days = data.auto_release_days;
        
        
        if (data.max_revision_count !== undefined) updatePayload.max_revision_count = data.max_revision_count;
        
        
        if (data.min_review_length !== undefined) updatePayload.min_review_length = data.min_review_length;
        
        
        if (data.new_user_verify_email !== undefined) updatePayload.new_user_verify_email = data.new_user_verify_email;
        
        
        if (data.tutor_two_factor_required !== undefined) updatePayload.tutor_two_factor_required = data.tutor_two_factor_required;
        
        
        if (data.maintenance_mode !== undefined) updatePayload.maintenance_mode = data.maintenance_mode;
        
        
        if (data.maintenance_message !== undefined) updatePayload.maintenance_message = data.maintenance_message;
        
        
        if (data.announcement_banner_enabled !== undefined) updatePayload.announcement_banner_enabled = data.announcement_banner_enabled;
        
        
        if (data.announcement_banner_text !== undefined) updatePayload.announcement_banner_text = data.announcement_banner_text;
        
        
        if (data.jitsi_sdk_key !== undefined) updatePayload.jitsi_sdk_key = data.jitsi_sdk_key;
        
        
        if (data.jitsi_sdk_secret !== undefined) updatePayload.jitsi_sdk_secret = data.jitsi_sdk_secret;
        
        
        updatePayload.updatedById = currentUser.id;

        await platform_config.update(updatePayload, {transaction});

        
        

        
        

        

        return platform_config;
    }

    static async deleteByIds(ids, options) {
        const currentUser = (options && options.currentUser) || { id: null };
        const transaction = (options && options.transaction) || undefined;

        const platform_config = await db.platform_config.findAll({
            where: {
                id: {
                    [Op.in]: ids,
                },
            },
            transaction,
        });

        await db.sequelize.transaction(async (transaction) => {
            for (const record of platform_config) {
                await record.update(
                    {deletedBy: currentUser.id},
                    {transaction}
                );
            }
            for (const record of platform_config) {
                await record.destroy({transaction});
            }
        });


        return platform_config;
    }

    static async remove(id, options) {
        const currentUser = (options && options.currentUser) || {id: null};
        const transaction = (options && options.transaction) || undefined;

        const platform_config = await db.platform_config.findByPk(id, options);

        await platform_config.update({
            deletedBy: currentUser.id
        }, {
            transaction,
        });

        await platform_config.destroy({
            transaction
        });

        return platform_config;
    }

    static async findBy(where, options) {
        const transaction = (options && options.transaction) || undefined;

        const platform_config = await db.platform_config.findOne(
            { where },
            { transaction },
        );

        if (!platform_config) {
            return platform_config;
        }

        const output = platform_config.get({plain: true});

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        

        return output;
    }

    static async findAll(
          filter,
           options
        ) {
        const limit = filter.limit || 0;
        let offset = 0;
        let where = {};
        const currentPage = +filter.page;

        

        

        offset = currentPage * limit;

        const orderBy = null;

    const transaction = (options && options.transaction) || undefined;

    let include = [



    ];

        if (filter) {
            if (filter.id) {
                where = {
                    ...where,
                    ['id']: Utils.uuid(filter.id),
                };
            }

            
            if (filter.maintenance_message) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'platform_config',
                        'maintenance_message',
                        filter.maintenance_message,
                    ),
                };
            }
            
            if (filter.announcement_banner_text) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'platform_config',
                        'announcement_banner_text',
                        filter.announcement_banner_text,
                    ),
                };
            }
            
            if (filter.jitsi_sdk_key) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'platform_config',
                        'jitsi_sdk_key',
                        filter.jitsi_sdk_key,
                    ),
                };
            }
            
            if (filter.jitsi_sdk_secret) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'platform_config',
                        'jitsi_sdk_secret',
                        filter.jitsi_sdk_secret,
                    ),
                };
            }
            

            
            

            
            if (filter.platform_fee_percentRange) {
                const [start, end] = filter.platform_fee_percentRange;

                if (start !== undefined && start !== null && start !== '') {
                    where = {
                        ...where,
                    platform_fee_percent: {
                    ...where.platform_fee_percent,
                            [Op.gte]: start,
                    },
                };
                }

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    platform_fee_percent: {
                    ...where.platform_fee_percent,
                            [Op.lte]: end,
                    },
                };
                }
            }
            
            if (filter.auto_release_daysRange) {
                const [start, end] = filter.auto_release_daysRange;

                if (start !== undefined && start !== null && start !== '') {
                    where = {
                        ...where,
                    auto_release_days: {
                    ...where.auto_release_days,
                            [Op.gte]: start,
                    },
                };
                }

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    auto_release_days: {
                    ...where.auto_release_days,
                            [Op.lte]: end,
                    },
                };
                }
            }
            
            if (filter.max_revision_countRange) {
                const [start, end] = filter.max_revision_countRange;

                if (start !== undefined && start !== null && start !== '') {
                    where = {
                        ...where,
                    max_revision_count: {
                    ...where.max_revision_count,
                            [Op.gte]: start,
                    },
                };
                }

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    max_revision_count: {
                    ...where.max_revision_count,
                            [Op.lte]: end,
                    },
                };
                }
            }
            
            if (filter.min_review_lengthRange) {
                const [start, end] = filter.min_review_lengthRange;

                if (start !== undefined && start !== null && start !== '') {
                    where = {
                        ...where,
                    min_review_length: {
                    ...where.min_review_length,
                            [Op.gte]: start,
                    },
                };
                }

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    min_review_length: {
                    ...where.min_review_length,
                            [Op.lte]: end,
                    },
                };
                }
            }
            

            if (filter.active !== undefined) {
                where = {
                    ...where,
                    active: filter.active === true || filter.active === 'true'
                };
            }

            
            if (filter.new_user_verify_email) {
                where = {
                    ...where,
                new_user_verify_email: filter.new_user_verify_email,
            };
            }
            
            if (filter.tutor_two_factor_required) {
                where = {
                    ...where,
                tutor_two_factor_required: filter.tutor_two_factor_required,
            };
            }
            
            if (filter.maintenance_mode) {
                where = {
                    ...where,
                maintenance_mode: filter.maintenance_mode,
            };
            }
            
            if (filter.announcement_banner_enabled) {
                where = {
                    ...where,
                announcement_banner_enabled: filter.announcement_banner_enabled,
            };
            }
            




            if (filter.createdAtRange) {
                const [start, end] = filter.createdAtRange;

                if (start !== undefined && start !== null && start !== '') {
                    where = {
                        ...where,
                        ['createdAt']: {
                            ...where.createdAt,
                            [Op.gte]: start,
                        },
                    };
                }

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                        ['createdAt']: {
                            ...where.createdAt,
                            [Op.lte]: end,
                        },
                    };
                }
            }
        }
        

        

        const queryOptions = {
            where,
            include,
            distinct: true,
            order: filter.field && filter.sort
                ? [[filter.field, filter.sort]]
                : [['createdAt', 'desc']],
            transaction: options?.transaction,
            logging: console.log
        };

        if (!options?.countOnly) {
            queryOptions.limit = limit ? Number(limit) : undefined;
            queryOptions.offset = offset ? Number(offset) : undefined;
        }

        try {
            const { rows, count } = await db.platform_config.findAndCountAll(queryOptions);

            return {
                rows: options?.countOnly ? [] : rows,
                count: count
            };
        } catch (error) {
            console.error('Error executing query:', error);
            throw error;
        }
    }

    static async findAllAutocomplete(query, limit, offset, ) {
        let where = {};
        
        

        if (query) {
            where = {
                [Op.or]: [
                    { ['id']: Utils.uuid(query) },
                    Utils.ilike(
                        'platform_config',
                        'announcement_banner_text',
                        query,
                    ),
                ],
            };
        }

        const records = await db.platform_config.findAll({
            attributes: [ 'id', 'announcement_banner_text' ],
            where,
            limit: limit ? Number(limit) : undefined,
            offset: offset ? Number(offset) : undefined,
            orderBy: [['announcement_banner_text', 'ASC']],
        });

        return records.map((record) => ({
            id: record.id,
            label: record.announcement_banner_text,
        }));
    }

    
};

