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

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

        const form_alarms = await db.form_alarms.create(
            {
                id: data.id || undefined,
        
        form_key: data.form_key
        ||
        null
            ,
            
        action: data.action
        ||
        null
            ,
            
        severity: data.severity
        ||
        null
            ,
            
        message_template: data.message_template
        ||
        null
            ,
            
        is_enabled: data.is_enabled
        ||
        false
        
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await form_alarms.setBusiness( data.business || null, {
            transaction,
        });
        

        

        

        return form_alarms;
    }
    

    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 form_alarmsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                form_key: item.form_key
            ||
            null
            ,
            
                action: item.action
            ||
            null
            ,
            
                severity: item.severity
            ||
            null
            ,
            
                message_template: item.message_template
            ||
            null
            ,
            
                is_enabled: item.is_enabled
            ||
            false
        
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return form_alarms;
    }

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

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


        

        const updatePayload = {};
        
        if (data.form_key !== undefined) updatePayload.form_key = data.form_key;
        
        
        if (data.action !== undefined) updatePayload.action = data.action;
        
        
        if (data.severity !== undefined) updatePayload.severity = data.severity;
        
        
        if (data.message_template !== undefined) updatePayload.message_template = data.message_template;
        
        
        if (data.is_enabled !== undefined) updatePayload.is_enabled = data.is_enabled;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.business !== undefined) {
            await form_alarms.setBusiness(
              
              data.business,
              
              { transaction }
            );
        }
        

        
        

        

        return form_alarms;
    }

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

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

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


        return form_alarms;
    }

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

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

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

        await form_alarms.destroy({
            transaction
        });

        return form_alarms;
    }

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

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

        if (!form_alarms) {
            return form_alarms;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.business = await form_alarms.getBusiness({
            transaction
        });
        
        

        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 = [

      {
        model: db.businesses,
        as: 'business',
        
        where: filter.business ? {
          [Op.or]: [
            { id: { [Op.in]: filter.business.split('|').map(term => Utils.uuid(term)) } },
            {
              trade_name: {
                [Op.or]: filter.business.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },



    ];

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

            
            if (filter.form_key) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'form_alarms',
                        'form_key',
                        filter.form_key,
                    ),
                };
            }
            
            if (filter.message_template) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'form_alarms',
                        'message_template',
                        filter.message_template,
                    ),
                };
            }
            

            
            

            

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

            
            if (filter.action) {
                where = {
                    ...where,
                action: filter.action,
            };
            }
            
            if (filter.severity) {
                where = {
                    ...where,
                severity: filter.severity,
            };
            }
            
            if (filter.is_enabled) {
                where = {
                    ...where,
                is_enabled: filter.is_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.form_alarms.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(
                        'form_alarms',
                        'form_key',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

