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

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

        const simulation_runs = await db.simulation_runs.create(
            {
                id: data.id || undefined,
        
        scenario_type: data.scenario_type
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        started_at: data.started_at
        ||
        null
            ,
            
        ended_at: data.ended_at
        ||
        null
            ,
            
        success_score: data.success_score
        ||
        null
            ,
            
        findings: data.findings
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await simulation_runs.setLab( data.lab || null, {
            transaction,
        });
        
        await simulation_runs.setInitiated_by( data.initiated_by || null, {
            transaction,
        });
        
        await simulation_runs.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        
        await simulation_runs.setAffected_assets(data.affected_assets || [], {
            transaction,
        });
        

        

        return simulation_runs;
    }
    

    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 simulation_runsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                scenario_type: item.scenario_type
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
                started_at: item.started_at
            ||
            null
            ,
            
                ended_at: item.ended_at
            ||
            null
            ,
            
                success_score: item.success_score
            ||
            null
            ,
            
                findings: item.findings
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return simulation_runs;
    }

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


        

        const updatePayload = {};
        
        if (data.scenario_type !== undefined) updatePayload.scenario_type = data.scenario_type;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.started_at !== undefined) updatePayload.started_at = data.started_at;
        
        
        if (data.ended_at !== undefined) updatePayload.ended_at = data.ended_at;
        
        
        if (data.success_score !== undefined) updatePayload.success_score = data.success_score;
        
        
        if (data.findings !== undefined) updatePayload.findings = data.findings;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.lab !== undefined) {
            await simulation_runs.setLab(
              
              data.lab,
              
              { transaction }
            );
        }
        
        if (data.initiated_by !== undefined) {
            await simulation_runs.setInitiated_by(
              
              data.initiated_by,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await simulation_runs.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        
        if (data.affected_assets !== undefined) {
            await simulation_runs.setAffected_assets(data.affected_assets, { transaction });
        }
        

        

        return simulation_runs;
    }

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

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

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


        return simulation_runs;
    }

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

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

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

        await simulation_runs.destroy({
            transaction
        });

        return simulation_runs;
    }

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

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

        if (!simulation_runs) {
            return simulation_runs;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.lab = await simulation_runs.getLab({
            transaction
        });
        
        
        output.initiated_by = await simulation_runs.getInitiated_by({
            transaction
        });
        
        
        output.affected_assets = await simulation_runs.getAffected_assets({
            transaction
        });
        
        
        output.organizations = await simulation_runs.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.simulation_labs,
        as: 'lab',
        
        where: filter.lab ? {
          [Op.or]: [
            { id: { [Op.in]: filter.lab.split('|').map(term => Utils.uuid(term)) } },
            {
              name: {
                [Op.or]: filter.lab.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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

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


      {
        model: db.assets,
        as: 'affected_assets',
        required: false,
      },


    ];

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

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

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

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

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

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

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

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

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

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

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

            
            if (filter.scenario_type) {
                where = {
                    ...where,
                scenario_type: filter.scenario_type,
            };
            }
            
            if (filter.status) {
                where = {
                    ...where,
                status: filter.status,
            };
            }
            


      

      

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

        where = {
          ...where,
          organizationsId: {[Op.or]: listItems}
        };
      }
      


      if (filter.affected_assets) {
        const searchTerms = filter.affected_assets.split('|');

        include = [
          {
            model: db.assets,
            as: 'affected_assets_filter',
            required: searchTerms.length > 0,
            where: searchTerms.length > 0 ? {
              [Op.or]: [
                { id: { [Op.in]: searchTerms.map(term => Utils.uuid(term)) } },
                { 
                  name: {
                    [Op.or]: searchTerms.map(term => ({ [Op.iLike]: `%${term}%` }))
                  }
                }
              ]
            } : undefined
          },
          ...include,
        ]
      }


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

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

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

    
};

