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

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

        const components = await db.components.create(
            {
                id: data.id || undefined,
        
        name: data.name
        ||
        null
            ,
            
        component_type: data.component_type
        ||
        null
            ,
            
        props: data.props
        ||
        null
            ,
            
        is_public: data.is_public
        ||
        false
        
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await components.setOwner( data.owner || null, {
            transaction,
        });
        
        await components.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

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

        return components;
    }
    

    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 componentsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                name: item.name
            ||
            null
            ,
            
                component_type: item.component_type
            ||
            null
            ,
            
                props: item.props
            ||
            null
            ,
            
                is_public: item.is_public
            ||
            false
        
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        
        for (let i = 0; i < components.length; i++) {
            await FileDBApi.replaceRelationFiles(
                {
                    belongsTo: db.components.getTableName(),
                    belongsToColumn: 'preview',
                    belongsToId: components[i].id,
                },
                data[i].preview,
                options,
            );
        }
        

        return components;
    }

    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 components = await db.components.findByPk(id, {}, {transaction});


        

        const updatePayload = {};
        
        if (data.name !== undefined) updatePayload.name = data.name;
        
        
        if (data.component_type !== undefined) updatePayload.component_type = data.component_type;
        
        
        if (data.props !== undefined) updatePayload.props = data.props;
        
        
        if (data.is_public !== undefined) updatePayload.is_public = data.is_public;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.owner !== undefined) {
            await components.setOwner(
              
              data.owner,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await components.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        

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

        return components;
    }

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

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

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


        return components;
    }

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

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

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

        await components.destroy({
            transaction
        });

        return components;
    }

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

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

        if (!components) {
            return components;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.preview = await components.getPreview({
            transaction
        });
        
        
        output.owner = await components.getOwner({
            transaction
        });
        
        
        output.organizations = await components.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.users,
        as: 'owner',
        
        where: filter.owner ? {
          [Op.or]: [
            { id: { [Op.in]: filter.owner.split('|').map(term => Utils.uuid(term)) } },
            {
              firstName: {
                [Op.or]: filter.owner.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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



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

    ];

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

            
            if (filter.name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'components',
                        'name',
                        filter.name,
                    ),
                };
            }
            
            if (filter.props) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'components',
                        'props',
                        filter.props,
                    ),
                };
            }
            

            
            

            

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

            
            if (filter.component_type) {
                where = {
                    ...where,
                component_type: filter.component_type,
            };
            }
            
            if (filter.is_public) {
                where = {
                    ...where,
                is_public: filter.is_public,
            };
            }
            


      

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

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

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

    
};

