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

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

        const alerts = await db.alerts.create(
            {
                id: data.id || undefined,
        
        type: data.type
        ||
        null
            ,
            
        severity: data.severity
        ||
        null
            ,
            
        title: data.title
        ||
        null
            ,
            
        message: data.message
        ||
        null
            ,
            
        triggered_at: data.triggered_at
        ||
        null
            ,
            
        due_at: data.due_at
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await alerts.setClient( data.client || null, {
            transaction,
        });
        
        await alerts.setProduct( data.product || null, {
            transaction,
        });
        
        await alerts.setInvoice( data.invoice || null, {
            transaction,
        });
        
        await alerts.setPoultry_lot( data.poultry_lot || null, {
            transaction,
        });
        
        await alerts.setAssigned_to_user( data.assigned_to_user || null, {
            transaction,
        });
        

        

        

        return alerts;
    }
    

    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 alertsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                type: item.type
            ||
            null
            ,
            
                severity: item.severity
            ||
            null
            ,
            
                title: item.title
            ||
            null
            ,
            
                message: item.message
            ||
            null
            ,
            
                triggered_at: item.triggered_at
            ||
            null
            ,
            
                due_at: item.due_at
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return alerts;
    }

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

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


        

        const updatePayload = {};
        
        if (data.type !== undefined) updatePayload.type = data.type;
        
        
        if (data.severity !== undefined) updatePayload.severity = data.severity;
        
        
        if (data.title !== undefined) updatePayload.title = data.title;
        
        
        if (data.message !== undefined) updatePayload.message = data.message;
        
        
        if (data.triggered_at !== undefined) updatePayload.triggered_at = data.triggered_at;
        
        
        if (data.due_at !== undefined) updatePayload.due_at = data.due_at;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.client !== undefined) {
            await alerts.setClient(
              
              data.client,
              
              { transaction }
            );
        }
        
        if (data.product !== undefined) {
            await alerts.setProduct(
              
              data.product,
              
              { transaction }
            );
        }
        
        if (data.invoice !== undefined) {
            await alerts.setInvoice(
              
              data.invoice,
              
              { transaction }
            );
        }
        
        if (data.poultry_lot !== undefined) {
            await alerts.setPoultry_lot(
              
              data.poultry_lot,
              
              { transaction }
            );
        }
        
        if (data.assigned_to_user !== undefined) {
            await alerts.setAssigned_to_user(
              
              data.assigned_to_user,
              
              { transaction }
            );
        }
        

        
        

        

        return alerts;
    }

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

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

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


        return alerts;
    }

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

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

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

        await alerts.destroy({
            transaction
        });

        return alerts;
    }

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

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

        if (!alerts) {
            return alerts;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.client = await alerts.getClient({
            transaction
        });
        
        
        output.product = await alerts.getProduct({
            transaction
        });
        
        
        output.invoice = await alerts.getInvoice({
            transaction
        });
        
        
        output.poultry_lot = await alerts.getPoultry_lot({
            transaction
        });
        
        
        output.assigned_to_user = await alerts.getAssigned_to_user({
            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.clients,
        as: 'client',
        
        where: filter.client ? {
          [Op.or]: [
            { id: { [Op.in]: filter.client.split('|').map(term => Utils.uuid(term)) } },
            {
              name: {
                [Op.or]: filter.client.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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

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

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

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



    ];

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

            
            if (filter.title) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'alerts',
                        'title',
                        filter.title,
                    ),
                };
            }
            
            if (filter.message) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'alerts',
                        'message',
                        filter.message,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

            
            if (filter.type) {
                where = {
                    ...where,
                type: filter.type,
            };
            }
            
            if (filter.severity) {
                where = {
                    ...where,
                severity: filter.severity,
            };
            }
            
            if (filter.status) {
                where = {
                    ...where,
                status: filter.status,
            };
            }
            


      

      

      

      

      



            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.alerts.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(
                        'alerts',
                        'title',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

