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

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

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

        

        

        

        return newsletter_subscribers;
    }
    

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

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

        // For each item created, replace relation files
        

        return newsletter_subscribers;
    }

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

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


        

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

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

        
        

        
        

        

        return newsletter_subscribers;
    }

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

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

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


        return newsletter_subscribers;
    }

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

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

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

        await newsletter_subscribers.destroy({
            transaction
        });

        return newsletter_subscribers;
    }

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

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

        if (!newsletter_subscribers) {
            return newsletter_subscribers;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        

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



    ];

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

            
            if (filter.email) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'newsletter_subscribers',
                        'email',
                        filter.email,
                    ),
                };
            }
            
            if (filter.full_name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'newsletter_subscribers',
                        'full_name',
                        filter.full_name,
                    ),
                };
            }
            
            if (filter.company_name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'newsletter_subscribers',
                        'company_name',
                        filter.company_name,
                    ),
                };
            }
            
            if (filter.country) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'newsletter_subscribers',
                        'country',
                        filter.country,
                    ),
                };
            }
            

            
            

            
            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.active !== undefined) {
                where = {
                    ...where,
                    active: filter.active === true || filter.active === 'true'
                };
            }

            
            if (filter.source) {
                where = {
                    ...where,
                source: filter.source,
            };
            }
            
            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_subscribers.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_subscribers',
                        'email',
                        query,
                    ),
                ],
            };
        }

        const records = await db.newsletter_subscribers.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,
        }));
    }

    
};

