
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,
        
        block_type: data.block_type
        ||
        null
            ,
            
        title: data.title
        ||
        null
            ,
            
        text_content: data.text_content
        ||
        null
            ,
            
        code_language: data.code_language
        ||
        null
            ,
            
        link_url: data.link_url
        ||
        null
            ,
            
        sort_order: data.sort_order
        ||
        null
            ,
            
        is_collapsed: data.is_collapsed
        ||
        false
        
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await blocks.setPage( data.page || null, {
            transaction,
        });
        
        await blocks.setParent_block( data.parent_block || null, {
            transaction,
        });
        
        await blocks.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

        
        await FileDBApi.replaceRelationFiles(
            {
                belongsTo: db.blocks.getTableName(),
                belongsToColumn: 'file_asset',
                belongsToId: blocks.id,
            },
            data.file_asset,
            options,
        );
        
        await FileDBApi.replaceRelationFiles(
            {
                belongsTo: db.blocks.getTableName(),
                belongsToColumn: 'image_asset',
                belongsToId: blocks.id,
            },
            data.image_asset,
            options,
        );
        

        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,
                
                block_type: item.block_type
            ||
            null
            ,
            
                title: item.title
            ||
            null
            ,
            
                text_content: item.text_content
            ||
            null
            ,
            
                code_language: item.code_language
            ||
            null
            ,
            
                link_url: item.link_url
            ||
            null
            ,
            
                sort_order: item.sort_order
            ||
            null
            ,
            
                is_collapsed: item.is_collapsed
            ||
            false
        
            ,
            
            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
        
        for (let i = 0; i < blocks.length; i++) {
            await FileDBApi.replaceRelationFiles(
                {
                    belongsTo: db.blocks.getTableName(),
                    belongsToColumn: 'file_asset',
                    belongsToId: blocks[i].id,
                },
                data[i].file_asset,
                options,
            );
        }
        
        for (let i = 0; i < blocks.length; i++) {
            await FileDBApi.replaceRelationFiles(
                {
                    belongsTo: db.blocks.getTableName(),
                    belongsToColumn: 'image_asset',
                    belongsToId: blocks[i].id,
                },
                data[i].image_asset,
                options,
            );
        }
        

        return blocks;
    }

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

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


        

        const updatePayload = {};
        
        if (data.block_type !== undefined) updatePayload.block_type = data.block_type;
        
        
        if (data.title !== undefined) updatePayload.title = data.title;
        
        
        if (data.text_content !== undefined) updatePayload.text_content = data.text_content;
        
        
        if (data.code_language !== undefined) updatePayload.code_language = data.code_language;
        
        
        if (data.link_url !== undefined) updatePayload.link_url = data.link_url;
        
        
        if (data.sort_order !== undefined) updatePayload.sort_order = data.sort_order;
        
        
        if (data.is_collapsed !== undefined) updatePayload.is_collapsed = data.is_collapsed;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.page !== undefined) {
            await blocks.setPage(
              
              data.page,
              
              { transaction }
            );
        }
        
        if (data.parent_block !== undefined) {
            await blocks.setParent_block(
              
              data.parent_block,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await blocks.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        

        
        await FileDBApi.replaceRelationFiles(
            {
                belongsTo: db.blocks.getTableName(),
                belongsToColumn: 'file_asset',
                belongsToId: blocks.id,
            },
            data.file_asset,
            options,
        );
        
        await FileDBApi.replaceRelationFiles(
            {
                belongsTo: db.blocks.getTableName(),
                belongsToColumn: 'image_asset',
                belongsToId: blocks.id,
            },
            data.image_asset,
            options,
        );
        

        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.page = await blocks.getPage({
            transaction
        });
        
        
        output.parent_block = await blocks.getParent_block({
            transaction
        });
        
        
        output.file_asset = await blocks.getFile_asset({
            transaction
        });
        
        
        output.image_asset = await blocks.getImage_asset({
            transaction
        });
        
        
        output.organizations = await blocks.getOrganizations({
            transaction
        });
        
        

        return output;
    }

    static async findAll(
          filter,
           globalAccess,  options
        ) {
        const limit = filter.limit || 0;
        let offset = 0;
        let where = {};
        const currentPage = +filter.page;

        
        const user = (options && options.currentUser) || null;
        const userOrganizations = (user && user.organizations?.id) || null;
        

        
        if (userOrganizations) {
            if (options?.currentUser?.organizationsId) {
                where.organizationsId = options.currentUser.organizationsId;
            }
        }
        

        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}%` }))
              }
            },
          ]
        } : {},
        
      },

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

      {
        model: db.organizations,
        as: 'organizations',
        
      },



      {
        model: db.file,
        as: 'file_asset',
      },

      {
        model: db.file,
        as: 'image_asset',
      },

    ];

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

            
            if (filter.title) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'blocks',
                        'title',
                        filter.title,
                    ),
                };
            }
            
            if (filter.text_content) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'blocks',
                        'text_content',
                        filter.text_content,
                    ),
                };
            }
            
            if (filter.code_language) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'blocks',
                        'code_language',
                        filter.code_language,
                    ),
                };
            }
            
            if (filter.link_url) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'blocks',
                        'link_url',
                        filter.link_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.block_type) {
                where = {
                    ...where,
                block_type: filter.block_type,
            };
            }
            
            if (filter.is_collapsed) {
                where = {
                    ...where,
                is_collapsed: filter.is_collapsed,
            };
            }
            


      

      

      
      if (filter.organizations) {
        const listItems = filter.organizations.split('|').map(item => {
          return  Utils.uuid(item)
        });

        where = {
          ...where,
          organizationsId: {[Op.or]: listItems}
        };
      }
      



            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,
                        },
                    };
                }
            }
        }
        

        
        if (globalAccess) {
            delete where.organizationsId;
        }
        

        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,  globalAccess, organizationId,) {
        let where = {};
        
        
        if (!globalAccess && organizationId) {
            where.organizationId = organizationId;
        }
        

        if (query) {
            where = {
                [Op.or]: [
                    { ['id']: Utils.uuid(query) },
                    Utils.ilike(
                        'blocks',
                        'title',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

