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

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

        const encryption_sessions = await db.encryption_sessions.create(
            {
                id: data.id || undefined,
        
        session_key_id: data.session_key_id
        ||
        null
            ,
            
        algorithm: data.algorithm
        ||
        null
            ,
            
        key_length_bits: data.key_length_bits
        ||
        null
            ,
            
        valid_from: data.valid_from
        ||
        null
            ,
            
        valid_until: data.valid_until
        ||
        null
            ,
            
        is_discarded: data.is_discarded
        ||
        false
        
            ,
            
        discarded_at: data.discarded_at
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await encryption_sessions.setChat( data.chat || null, {
            transaction,
        });
        
        await encryption_sessions.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

        

        return encryption_sessions;
    }
    

    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 encryption_sessionsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                session_key_id: item.session_key_id
            ||
            null
            ,
            
                algorithm: item.algorithm
            ||
            null
            ,
            
                key_length_bits: item.key_length_bits
            ||
            null
            ,
            
                valid_from: item.valid_from
            ||
            null
            ,
            
                valid_until: item.valid_until
            ||
            null
            ,
            
                is_discarded: item.is_discarded
            ||
            false
        
            ,
            
                discarded_at: item.discarded_at
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return encryption_sessions;
    }

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


        

        const updatePayload = {};
        
        if (data.session_key_id !== undefined) updatePayload.session_key_id = data.session_key_id;
        
        
        if (data.algorithm !== undefined) updatePayload.algorithm = data.algorithm;
        
        
        if (data.key_length_bits !== undefined) updatePayload.key_length_bits = data.key_length_bits;
        
        
        if (data.valid_from !== undefined) updatePayload.valid_from = data.valid_from;
        
        
        if (data.valid_until !== undefined) updatePayload.valid_until = data.valid_until;
        
        
        if (data.is_discarded !== undefined) updatePayload.is_discarded = data.is_discarded;
        
        
        if (data.discarded_at !== undefined) updatePayload.discarded_at = data.discarded_at;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.chat !== undefined) {
            await encryption_sessions.setChat(
              
              data.chat,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await encryption_sessions.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        

        

        return encryption_sessions;
    }

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

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

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


        return encryption_sessions;
    }

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

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

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

        await encryption_sessions.destroy({
            transaction
        });

        return encryption_sessions;
    }

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

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

        if (!encryption_sessions) {
            return encryption_sessions;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.chat = await encryption_sessions.getChat({
            transaction
        });
        
        
        output.organizations = await encryption_sessions.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.chats,
        as: 'chat',
        
        where: filter.chat ? {
          [Op.or]: [
            { id: { [Op.in]: filter.chat.split('|').map(term => Utils.uuid(term)) } },
            {
              title: {
                [Op.or]: filter.chat.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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



    ];

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

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

            
            
            if (filter.calendarStart && filter.calendarEnd) {
                where = {
                    ...where,
                    [Op.or]: [
                        {
                            valid_from: {
                                [Op.between]: [filter.calendarStart, filter.calendarEnd],
                            },
                    },
                {
                    valid_until: {
                        [Op.between]: [filter.calendarStart, filter.calendarEnd],
                    },
                },
                ],
            };
            }
            

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

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

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

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

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

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

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

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

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

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

            
            if (filter.algorithm) {
                where = {
                    ...where,
                algorithm: filter.algorithm,
            };
            }
            
            if (filter.is_discarded) {
                where = {
                    ...where,
                is_discarded: filter.is_discarded,
            };
            }
            


      

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

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

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

    
};

