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

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

        const kms_configs = await db.kms_configs.create(
            {
                id: data.id || undefined,
        
        kms_type: data.kms_type
        ||
        null
            ,
            
        name: data.name
        ||
        null
            ,
            
        key_uri: data.key_uri
        ||
        null
            ,
            
        kms_status: data.kms_status
        ||
        null
            ,
            
        last_rotated_at: data.last_rotated_at
        ||
        null
            ,
            
        auto_rotate_enabled: data.auto_rotate_enabled
        ||
        false
        
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

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

        

        

        return kms_configs;
    }
    

    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 kms_configsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                kms_type: item.kms_type
            ||
            null
            ,
            
                name: item.name
            ||
            null
            ,
            
                key_uri: item.key_uri
            ||
            null
            ,
            
                kms_status: item.kms_status
            ||
            null
            ,
            
                last_rotated_at: item.last_rotated_at
            ||
            null
            ,
            
                auto_rotate_enabled: item.auto_rotate_enabled
            ||
            false
        
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return kms_configs;
    }

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


        

        const updatePayload = {};
        
        if (data.kms_type !== undefined) updatePayload.kms_type = data.kms_type;
        
        
        if (data.name !== undefined) updatePayload.name = data.name;
        
        
        if (data.key_uri !== undefined) updatePayload.key_uri = data.key_uri;
        
        
        if (data.kms_status !== undefined) updatePayload.kms_status = data.kms_status;
        
        
        if (data.last_rotated_at !== undefined) updatePayload.last_rotated_at = data.last_rotated_at;
        
        
        if (data.auto_rotate_enabled !== undefined) updatePayload.auto_rotate_enabled = data.auto_rotate_enabled;
        
        
        updatePayload.updatedById = currentUser.id;

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

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

        
        

        

        return kms_configs;
    }

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

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

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


        return kms_configs;
    }

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

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

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

        await kms_configs.destroy({
            transaction
        });

        return kms_configs;
    }

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

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

        if (!kms_configs) {
            return kms_configs;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.tenant = await kms_configs.getTenant({
            transaction
        });
        
        
        output.organizations = await kms_configs.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.organizations,
        as: 'organizations',
        
      },



    ];

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

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

            
            

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

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

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

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

            
            if (filter.kms_type) {
                where = {
                    ...where,
                kms_type: filter.kms_type,
            };
            }
            
            if (filter.kms_status) {
                where = {
                    ...where,
                kms_status: filter.kms_status,
            };
            }
            
            if (filter.auto_rotate_enabled) {
                where = {
                    ...where,
                auto_rotate_enabled: filter.auto_rotate_enabled,
            };
            }
            


      

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

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

    
};

