
const db = require('../models');
const Utils = require('../utils');



const Sequelize = db.Sequelize;
const Op = Sequelize.Op;

module.exports = class Publish_eventsDBApi {
    

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

        const publish_events = await db.publish_events.create(
            {
                id: data.id || undefined,
        
        title: data.title
        ||
        null
            ,
            
        description: data.description
        ||
        null
            ,
        
        from_environment: data.from_environment
        ||
        null
            ,
            
        to_environment: data.to_environment
        ||
        null
            ,
            
        started_at: data.started_at
        ||
        null
            ,
            
        finished_at: data.finished_at
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        error_message: data.error_message
        ||
        null
            ,
            
        pages_copied: data.pages_copied
        ||
        null
            ,
            
        transitions_copied: data.transitions_copied
        ||
        null
            ,
            
        audios_copied: data.audios_copied
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await publish_events.setProject( data.project || null, {
            transaction,
        });
        
        await publish_events.setUser( data.user || null, {
            transaction,
        });
        

        

        

        return publish_events;
    }
    

    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 publish_eventsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                title: item.title
            ||
            null
            ,
            
                description: item.description
            ||
            null
            ,
                
                from_environment: item.from_environment
            ||
            null
            ,
            
                to_environment: item.to_environment
            ||
            null
            ,
            
                started_at: item.started_at
            ||
            null
            ,
            
                finished_at: item.finished_at
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
                error_message: item.error_message
            ||
            null
            ,
            
                pages_copied: item.pages_copied
            ||
            null
            ,
            
                transitions_copied: item.transitions_copied
            ||
            null
            ,
            
                audios_copied: item.audios_copied
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return publish_events;
    }

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

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


        

        const updatePayload = {};
        
        if (data.title !== undefined) updatePayload.title = data.title;
        
        
        if (data.description !== undefined) updatePayload.description = data.description;
        
        
        if (data.from_environment !== undefined) updatePayload.from_environment = data.from_environment;
        
        
        if (data.to_environment !== undefined) updatePayload.to_environment = data.to_environment;
        
        
        if (data.started_at !== undefined) updatePayload.started_at = data.started_at;
        
        
        if (data.finished_at !== undefined) updatePayload.finished_at = data.finished_at;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.error_message !== undefined) updatePayload.error_message = data.error_message;
        
        
        if (data.pages_copied !== undefined) updatePayload.pages_copied = data.pages_copied;
        
        
        if (data.transitions_copied !== undefined) updatePayload.transitions_copied = data.transitions_copied;
        
        
        if (data.audios_copied !== undefined) updatePayload.audios_copied = data.audios_copied;
        
        
        updatePayload.updatedById = currentUser.id;

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

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

        
        

        

        return publish_events;
    }

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

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

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


        return publish_events;
    }

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

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

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

        await publish_events.destroy({
            transaction
        });

        return publish_events;
    }

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

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

        if (!publish_events) {
            return publish_events;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.project = await publish_events.getProject({
            transaction
        });
        
        
        output.user = await publish_events.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;

    let include = [

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

      {
        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.title) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'publish_events',
                        'title',
                        filter.title,
                    ),
                };
            }
            
            if (filter.description) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'publish_events',
                        'description',
                        filter.description,
                    ),
                };
            }
            
            
            if (filter.error_message) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'publish_events',
                        'error_message',
                        filter.error_message,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

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

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

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

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

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

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

            
            if (filter.from_environment) {
                where = {
                    ...where,
                from_environment: filter.from_environment,
            };
            }
            
            if (filter.to_environment) {
                where = {
                    ...where,
                to_environment: filter.to_environment,
            };
            }
            
            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.publish_events.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(
                        'publish_events',
                        'status',
                        query,
                    ),
                ],
            };
        }

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

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

    
};
