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

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

        const newsletter_subscriptions = await db.newsletter_subscriptions.create(
            {
                id: data.id || undefined,
        
        email: data.email
        ||
        null
            ,
            
        is_confirmed: data.is_confirmed
        ||
        false
        
            ,
            
        subscribed_at: data.subscribed_at
        ||
        null
            ,
            
        unsubscribed_at: data.unsubscribed_at
        ||
        null
            ,
            
        source: data.source
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await newsletter_subscriptions.setUser( data.user || null, {
            transaction,
        });
        

        

        

        return newsletter_subscriptions;
    }
    

    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 newsletter_subscriptionsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                email: item.email
            ||
            null
            ,
            
                is_confirmed: item.is_confirmed
            ||
            false
        
            ,
            
                subscribed_at: item.subscribed_at
            ||
            null
            ,
            
                unsubscribed_at: item.unsubscribed_at
            ||
            null
            ,
            
                source: item.source
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return newsletter_subscriptions;
    }

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

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


        

        const updatePayload = {};
        
        if (data.email !== undefined) updatePayload.email = data.email;
        
        
        if (data.is_confirmed !== undefined) updatePayload.is_confirmed = data.is_confirmed;
        
        
        if (data.subscribed_at !== undefined) updatePayload.subscribed_at = data.subscribed_at;
        
        
        if (data.unsubscribed_at !== undefined) updatePayload.unsubscribed_at = data.unsubscribed_at;
        
        
        if (data.source !== undefined) updatePayload.source = data.source;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.user !== undefined) {
            await newsletter_subscriptions.setUser(
              
              data.user,
              
              { transaction }
            );
        }
        

        
        

        

        return newsletter_subscriptions;
    }

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

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

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


        return newsletter_subscriptions;
    }

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

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

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

        await newsletter_subscriptions.destroy({
            transaction
        });

        return newsletter_subscriptions;
    }

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

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

        if (!newsletter_subscriptions) {
            return newsletter_subscriptions;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.user = await newsletter_subscriptions.getUser({
            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.users,
        as: 'user',
        
        where: filter.user ? {
          [Op.or]: [
            { id: { [Op.in]: filter.user.split('|').map(term => Utils.uuid(term)) } },
            {
              firstName: {
                [Op.or]: filter.user.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },



    ];

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

            
            if (filter.email) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'newsletter_subscriptions',
                        'email',
                        filter.email,
                    ),
                };
            }
            
            if (filter.source) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'newsletter_subscriptions',
                        'source',
                        filter.source,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

            
            if (filter.is_confirmed) {
                where = {
                    ...where,
                is_confirmed: filter.is_confirmed,
            };
            }
            


      



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

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

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

    
};

