
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 Support_settingsDBApi {
    

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

        const support_settings = await db.support_settings.create(
            {
                id: data.id || undefined,
        
        support_email: data.support_email
        ||
        null
            ,
            
        support_phone: data.support_phone
        ||
        null
            ,
            
        support_hours: data.support_hours
        ||
        null
            ,
            
        privacy_policy_url: data.privacy_policy_url
        ||
        null
            ,
            
        terms_url: data.terms_url
        ||
        null
            ,
            
        app_version_notes: data.app_version_notes
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await support_settings.setSchools( data.schools || null, {
            transaction,
        });
        

        

        

        return support_settings;
    }
    

    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 support_settingsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                support_email: item.support_email
            ||
            null
            ,
            
                support_phone: item.support_phone
            ||
            null
            ,
            
                support_hours: item.support_hours
            ||
            null
            ,
            
                privacy_policy_url: item.privacy_policy_url
            ||
            null
            ,
            
                terms_url: item.terms_url
            ||
            null
            ,
            
                app_version_notes: item.app_version_notes
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return support_settings;
    }

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

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


        

        const updatePayload = {};
        
        if (data.support_email !== undefined) updatePayload.support_email = data.support_email;
        
        
        if (data.support_phone !== undefined) updatePayload.support_phone = data.support_phone;
        
        
        if (data.support_hours !== undefined) updatePayload.support_hours = data.support_hours;
        
        
        if (data.privacy_policy_url !== undefined) updatePayload.privacy_policy_url = data.privacy_policy_url;
        
        
        if (data.terms_url !== undefined) updatePayload.terms_url = data.terms_url;
        
        
        if (data.app_version_notes !== undefined) updatePayload.app_version_notes = data.app_version_notes;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.schools !== undefined) {
            await support_settings.setSchools(
              
              data.schools,
              
              { transaction }
            );
        }
        

        
        

        

        return support_settings;
    }

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

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

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


        return support_settings;
    }

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

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

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

        await support_settings.destroy({
            transaction
        });

        return support_settings;
    }

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

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

        if (!support_settings) {
            return support_settings;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.schools = await support_settings.getSchools({
            transaction
        });
        
        

        return output;
    }

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

        
        const user = (options && options.currentUser) || null;
        const userSchools = (user && user.schools?.id) || null;
        

        
        if (userSchools) {
            if (options?.currentUser?.schoolsId) {
                where.schoolsId = options.currentUser.schoolsId;
            }
        }
        

        offset = currentPage * limit;

        const orderBy = null;

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

    let include = [

      {
        model: db.schools,
        as: 'schools',
        
      },



    ];

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

            
            if (filter.support_email) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'support_settings',
                        'support_email',
                        filter.support_email,
                    ),
                };
            }
            
            if (filter.support_phone) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'support_settings',
                        'support_phone',
                        filter.support_phone,
                    ),
                };
            }
            
            if (filter.support_hours) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'support_settings',
                        'support_hours',
                        filter.support_hours,
                    ),
                };
            }
            
            if (filter.privacy_policy_url) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'support_settings',
                        'privacy_policy_url',
                        filter.privacy_policy_url,
                    ),
                };
            }
            
            if (filter.terms_url) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'support_settings',
                        'terms_url',
                        filter.terms_url,
                    ),
                };
            }
            
            if (filter.app_version_notes) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'support_settings',
                        'app_version_notes',
                        filter.app_version_notes,
                    ),
                };
            }
            

            
            

            

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

            


      
      if (filter.schools) {
        const listItems = filter.schools.split('|').map(item => {
          return  Utils.uuid(item)
        });

        where = {
          ...where,
          schoolsId: {[Op.or]: listItems}
        };
      }
      



            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,
                        },
                    };
                }
            }
        }
        

        
        if (globalAccess) {
            delete where.schoolsId;
        }
        

        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.support_settings.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,  globalAccess, organizationId,) {
        let where = {};
        
        
        if (!globalAccess && organizationId) {
            where.organizationId = organizationId;
        }
        

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

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

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

    
};

