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

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

        const blocks = await db.blocks.create(
            {
                id: data.id || undefined,
        
        reason: data.reason
        ||
        null
            ,
            
        blocked_at: data.blocked_at
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await blocks.setBlocker( data.blocker || null, {
            transaction,
        });
        
        await blocks.setBlocked( data.blocked || null, {
            transaction,
        });
        

        

        

        return blocks;
    }
    

    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 blocksData = data.map((item, index) => ({
                id: item.id || undefined,
                
                reason: item.reason
            ||
            null
            ,
            
                blocked_at: item.blocked_at
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return blocks;
    }

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

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


        

        const updatePayload = {};
        
        if (data.reason !== undefined) updatePayload.reason = data.reason;
        
        
        if (data.blocked_at !== undefined) updatePayload.blocked_at = data.blocked_at;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.blocker !== undefined) {
            await blocks.setBlocker(
              
              data.blocker,
              
              { transaction }
            );
        }
        
        if (data.blocked !== undefined) {
            await blocks.setBlocked(
              
              data.blocked,
              
              { transaction }
            );
        }
        

        
        

        

        return blocks;
    }

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

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

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


        return blocks;
    }

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

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

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

        await blocks.destroy({
            transaction
        });

        return blocks;
    }

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

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

        if (!blocks) {
            return blocks;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.blocker = await blocks.getBlocker({
            transaction
        });
        
        
        output.blocked = await blocks.getBlocked({
            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: 'blocker',
        
        where: filter.blocker ? {
          [Op.or]: [
            { id: { [Op.in]: filter.blocker.split('|').map(term => Utils.uuid(term)) } },
            {
              firstName: {
                [Op.or]: filter.blocker.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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



    ];

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

            
            if (filter.reason) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'blocks',
                        'reason',
                        filter.reason,
                    ),
                };
            }
            

            
            

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

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

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

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

            


      

      



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

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

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

    
};

