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

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

        const import_templates = await db.import_templates.create(
            {
                id: data.id || undefined,
        
        name: data.name
        ||
        null
            ,
            
        file_type: data.file_type
        ||
        null
            ,
            
        description: data.description
        ||
        null
            ,
            
        is_active: data.is_active
        ||
        false
        
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await import_templates.setTenant( data.tenant || null, {
            transaction,
        });
        
        await import_templates.setData_entity( data.data_entity || null, {
            transaction,
        });
        
        await import_templates.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

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

        return import_templates;
    }
    

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

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

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

        return import_templates;
    }

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


        

        const updatePayload = {};
        
        if (data.name !== undefined) updatePayload.name = data.name;
        
        
        if (data.file_type !== undefined) updatePayload.file_type = data.file_type;
        
        
        if (data.description !== undefined) updatePayload.description = data.description;
        
        
        if (data.is_active !== undefined) updatePayload.is_active = data.is_active;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.tenant !== undefined) {
            await import_templates.setTenant(
              
              data.tenant,
              
              { transaction }
            );
        }
        
        if (data.data_entity !== undefined) {
            await import_templates.setData_entity(
              
              data.data_entity,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await import_templates.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        

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

        return import_templates;
    }

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

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

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


        return import_templates;
    }

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

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

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

        await import_templates.destroy({
            transaction
        });

        return import_templates;
    }

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

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

        if (!import_templates) {
            return import_templates;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.tenant = await import_templates.getTenant({
            transaction
        });
        
        
        output.data_entity = await import_templates.getData_entity({
            transaction
        });
        
        
        output.template_file = await import_templates.getTemplate_file({
            transaction
        });
        
        
        output.organizations = await import_templates.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.tenants,
        as: 'tenant',
        
        where: filter.tenant ? {
          [Op.or]: [
            { id: { [Op.in]: filter.tenant.split('|').map(term => Utils.uuid(term)) } },
            {
              name: {
                [Op.or]: filter.tenant.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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

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



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

    ];

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

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

            
            

            

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

            
            if (filter.file_type) {
                where = {
                    ...where,
                file_type: filter.file_type,
            };
            }
            
            if (filter.is_active) {
                where = {
                    ...where,
                is_active: filter.is_active,
            };
            }
            


      

      

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

        const records = await db.import_templates.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,
        }));
    }

    
};

