
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const TenantAccess = require('./tenantAccess');



const Sequelize = db.Sequelize;
const Op = Sequelize.Op;

module.exports = class Connected_systemsDBApi {
    

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

        const connected_systems = await db.connected_systems.create(
            {
                id: data.id || undefined,
        
        system_name: data.system_name
        ||
        null
            ,
            
        system_type: data.system_type
        ||
        null
            ,
            
        vendor: data.vendor
        ||
        null
            ,
            
        environment: data.environment
        ||
        null
            ,
            
        owner: data.owner
        ||
        null
            ,
            
        connection_status: data.connection_status
        ||
        null
            ,
            
        last_successful_sync_at: data.last_successful_sync_at
        ||
        null
            ,
            
        connection_health_notes: data.connection_health_notes
        ||
        null
            ,
            
        source_of_truth_flag: data.source_of_truth_flag
        ||
        false
        
            ,
            
        notes: data.notes
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await connected_systems.setOrganization(currentUser.organization.id || null, {
            transaction,
        });
        

        

        

        return connected_systems;
    }
    

    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 connected_systemsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                system_name: item.system_name
            ||
            null
            ,
            
                system_type: item.system_type
            ||
            null
            ,
            
                vendor: item.vendor
            ||
            null
            ,
            
                environment: item.environment
            ||
            null
            ,
            
                owner: item.owner
            ||
            null
            ,
            
                connection_status: item.connection_status
            ||
            null
            ,
            
                last_successful_sync_at: item.last_successful_sync_at
            ||
            null
            ,
            
                connection_health_notes: item.connection_health_notes
            ||
            null
            ,
            
                source_of_truth_flag: item.source_of_truth_flag
            ||
            false
        
            ,
            
                notes: item.notes
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return connected_systems;
    }

    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 connected_systems = await TenantAccess.findByPkOrThrow(db.connected_systems, id, options);


        

        const updatePayload = {};
        
        if (data.system_name !== undefined) updatePayload.system_name = data.system_name;
        
        
        if (data.system_type !== undefined) updatePayload.system_type = data.system_type;
        
        
        if (data.vendor !== undefined) updatePayload.vendor = data.vendor;
        
        
        if (data.environment !== undefined) updatePayload.environment = data.environment;
        
        
        if (data.owner !== undefined) updatePayload.owner = data.owner;
        
        
        if (data.connection_status !== undefined) updatePayload.connection_status = data.connection_status;
        
        
        if (data.last_successful_sync_at !== undefined) updatePayload.last_successful_sync_at = data.last_successful_sync_at;
        
        
        if (data.connection_health_notes !== undefined) updatePayload.connection_health_notes = data.connection_health_notes;
        
        
        if (data.source_of_truth_flag !== undefined) updatePayload.source_of_truth_flag = data.source_of_truth_flag;
        
        
        if (data.notes !== undefined) updatePayload.notes = data.notes;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.organization !== undefined) {
            await connected_systems.setOrganization(
              
              (globalAccess ? data.organization : currentUser.organization.id),
              
              { transaction }
            );
        }
        

        
        

        

        return connected_systems;
    }

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

        const connected_systems = await TenantAccess.findAllByIds(db.connected_systems, ids, options);

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


        return connected_systems;
    }

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

        const connected_systems = await TenantAccess.findByPkOrThrow(db.connected_systems, id, options);

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

        await connected_systems.destroy({
            transaction
        });

        return connected_systems;
    }

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

        const connected_systems = await TenantAccess.findOne(db.connected_systems, where, options);

        if (!connected_systems) {
            return connected_systems;
        }

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

        
        
        
        
        
        
        
        
        
        
        output.evidence_models_source_system = await connected_systems.getEvidence_models_source_system({
            transaction
        });
        
        
        output.artifacts_source_system = await connected_systems.getArtifacts_source_system({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.organization = await connected_systems.getOrganization({
            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.organizations,
        as: 'organization',
        
      },



    ];

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

            
            if (filter.system_name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'connected_systems',
                        'system_name',
                        filter.system_name,
                    ),
                };
            }
            
            if (filter.vendor) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'connected_systems',
                        'vendor',
                        filter.vendor,
                    ),
                };
            }
            
            if (filter.owner) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'connected_systems',
                        'owner',
                        filter.owner,
                    ),
                };
            }
            
            if (filter.connection_health_notes) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'connected_systems',
                        'connection_health_notes',
                        filter.connection_health_notes,
                    ),
                };
            }
            
            if (filter.notes) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'connected_systems',
                        'notes',
                        filter.notes,
                    ),
                };
            }
            

            
            

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

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

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

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

            
            if (filter.system_type) {
                where = {
                    ...where,
                system_type: filter.system_type,
            };
            }
            
            if (filter.environment) {
                where = {
                    ...where,
                environment: filter.environment,
            };
            }
            
            if (filter.connection_status) {
                where = {
                    ...where,
                connection_status: filter.connection_status,
            };
            }
            
            if (filter.source_of_truth_flag) {
                where = {
                    ...where,
                source_of_truth_flag: filter.source_of_truth_flag,
            };
            }
            


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

        where = {
          ...where,
          organizationId: {[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.connected_systems.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(
                        'connected_systems',
                        'system_name',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

