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

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

        const cta_buttons = await db.cta_buttons.create(
            {
                id: data.id || undefined,
        
        label: data.label
        ||
        null
            ,
            
        cta_type: data.cta_type
        ||
        null
            ,
            
        url: data.url
        ||
        null
            ,
            
        style_variant: data.style_variant
        ||
        null
            ,
            
        open_in_new_tab: data.open_in_new_tab
        ||
        false
        
            ,
            
        sort_order: data.sort_order
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await cta_buttons.setPage( data.page || null, {
            transaction,
        });
        

        

        

        return cta_buttons;
    }
    

    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 cta_buttonsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                label: item.label
            ||
            null
            ,
            
                cta_type: item.cta_type
            ||
            null
            ,
            
                url: item.url
            ||
            null
            ,
            
                style_variant: item.style_variant
            ||
            null
            ,
            
                open_in_new_tab: item.open_in_new_tab
            ||
            false
        
            ,
            
                sort_order: item.sort_order
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return cta_buttons;
    }

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

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


        

        const updatePayload = {};
        
        if (data.label !== undefined) updatePayload.label = data.label;
        
        
        if (data.cta_type !== undefined) updatePayload.cta_type = data.cta_type;
        
        
        if (data.url !== undefined) updatePayload.url = data.url;
        
        
        if (data.style_variant !== undefined) updatePayload.style_variant = data.style_variant;
        
        
        if (data.open_in_new_tab !== undefined) updatePayload.open_in_new_tab = data.open_in_new_tab;
        
        
        if (data.sort_order !== undefined) updatePayload.sort_order = data.sort_order;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.page !== undefined) {
            await cta_buttons.setPage(
              
              data.page,
              
              { transaction }
            );
        }
        

        
        

        

        return cta_buttons;
    }

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

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

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


        return cta_buttons;
    }

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

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

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

        await cta_buttons.destroy({
            transaction
        });

        return cta_buttons;
    }

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

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

        if (!cta_buttons) {
            return cta_buttons;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.page = await cta_buttons.getPage({
            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.pages,
        as: 'page',
        
        where: filter.page ? {
          [Op.or]: [
            { id: { [Op.in]: filter.page.split('|').map(term => Utils.uuid(term)) } },
            {
              title: {
                [Op.or]: filter.page.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },



    ];

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

            
            if (filter.label) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'cta_buttons',
                        'label',
                        filter.label,
                    ),
                };
            }
            
            if (filter.url) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'cta_buttons',
                        'url',
                        filter.url,
                    ),
                };
            }
            

            
            

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

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

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

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

            
            if (filter.cta_type) {
                where = {
                    ...where,
                cta_type: filter.cta_type,
            };
            }
            
            if (filter.style_variant) {
                where = {
                    ...where,
                style_variant: filter.style_variant,
            };
            }
            
            if (filter.open_in_new_tab) {
                where = {
                    ...where,
                open_in_new_tab: filter.open_in_new_tab,
            };
            }
            


      



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

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

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

    
};

