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

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

        const marketing_campaigns = await db.marketing_campaigns.create(
            {
                id: data.id || undefined,
        
        campaign_name: data.campaign_name
        ||
        null
            ,
            
        channel: data.channel
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        scheduled_at: data.scheduled_at
        ||
        null
            ,
            
        sent_at: data.sent_at
        ||
        null
            ,
            
        message_body: data.message_body
        ||
        null
            ,
            
        segment_type: data.segment_type
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await marketing_campaigns.setBranch( data.branch || null, {
            transaction,
        });
        
        await marketing_campaigns.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

        

        return marketing_campaigns;
    }
    

    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 marketing_campaignsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                campaign_name: item.campaign_name
            ||
            null
            ,
            
                channel: item.channel
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
                scheduled_at: item.scheduled_at
            ||
            null
            ,
            
                sent_at: item.sent_at
            ||
            null
            ,
            
                message_body: item.message_body
            ||
            null
            ,
            
                segment_type: item.segment_type
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return marketing_campaigns;
    }

    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 marketing_campaigns = await db.marketing_campaigns.findByPk(id, {}, {transaction});


        

        const updatePayload = {};
        
        if (data.campaign_name !== undefined) updatePayload.campaign_name = data.campaign_name;
        
        
        if (data.channel !== undefined) updatePayload.channel = data.channel;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.scheduled_at !== undefined) updatePayload.scheduled_at = data.scheduled_at;
        
        
        if (data.sent_at !== undefined) updatePayload.sent_at = data.sent_at;
        
        
        if (data.message_body !== undefined) updatePayload.message_body = data.message_body;
        
        
        if (data.segment_type !== undefined) updatePayload.segment_type = data.segment_type;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.branch !== undefined) {
            await marketing_campaigns.setBranch(
              
              data.branch,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await marketing_campaigns.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        

        

        return marketing_campaigns;
    }

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

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

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


        return marketing_campaigns;
    }

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

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

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

        await marketing_campaigns.destroy({
            transaction
        });

        return marketing_campaigns;
    }

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

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

        if (!marketing_campaigns) {
            return marketing_campaigns;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.campaign_recipients_campaign = await marketing_campaigns.getCampaign_recipients_campaign({
            transaction
        });
        
        
        
        
        output.branch = await marketing_campaigns.getBranch({
            transaction
        });
        
        
        output.organizations = await marketing_campaigns.getOrganizations({
            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 userOrganizations = (user && user.organizations?.id) || null;
        

        
        if (userOrganizations) {
            if (options?.currentUser?.organizationsId) {
                where.organizationsId = options.currentUser.organizationsId;
            }
        }
        

        offset = currentPage * limit;

        const orderBy = null;

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

    let include = [

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

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



    ];

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

            
            if (filter.campaign_name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'marketing_campaigns',
                        'campaign_name',
                        filter.campaign_name,
                    ),
                };
            }
            
            if (filter.message_body) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'marketing_campaigns',
                        'message_body',
                        filter.message_body,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

            
            if (filter.channel) {
                where = {
                    ...where,
                channel: filter.channel,
            };
            }
            
            if (filter.status) {
                where = {
                    ...where,
                status: filter.status,
            };
            }
            
            if (filter.segment_type) {
                where = {
                    ...where,
                segment_type: filter.segment_type,
            };
            }
            


      

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

        where = {
          ...where,
          organizationsId: {[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.organizationsId;
        }
        

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

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

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

    
};

