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

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

        const access_review_items = await db.access_review_items.create(
            {
                id: data.id || undefined,
        
        subject_display_name: data.subject_display_name
        ||
        null
            ,
            
        subject_identifier: data.subject_identifier
        ||
        null
            ,
            
        system_name: data.system_name
        ||
        null
            ,
            
        entitlements_reviewed: data.entitlements_reviewed
        ||
        null
            ,
            
        reviewer_decision: data.reviewer_decision
        ||
        null
            ,
            
        justification: data.justification
        ||
        null
            ,
            
        action_required: data.action_required
        ||
        false
        
            ,
            
        completed_at: data.completed_at
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await access_review_items.setOrganization(currentUser.organization.id || null, {
            transaction,
        });
        
        await access_review_items.setAccess_review( data.access_review || null, {
            transaction,
        });
        

        

        

        return access_review_items;
    }
    

    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 access_review_itemsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                subject_display_name: item.subject_display_name
            ||
            null
            ,
            
                subject_identifier: item.subject_identifier
            ||
            null
            ,
            
                system_name: item.system_name
            ||
            null
            ,
            
                entitlements_reviewed: item.entitlements_reviewed
            ||
            null
            ,
            
                reviewer_decision: item.reviewer_decision
            ||
            null
            ,
            
                justification: item.justification
            ||
            null
            ,
            
                action_required: item.action_required
            ||
            false
        
            ,
            
                completed_at: item.completed_at
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return access_review_items;
    }

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


        

        const updatePayload = {};
        
        if (data.subject_display_name !== undefined) updatePayload.subject_display_name = data.subject_display_name;
        
        
        if (data.subject_identifier !== undefined) updatePayload.subject_identifier = data.subject_identifier;
        
        
        if (data.system_name !== undefined) updatePayload.system_name = data.system_name;
        
        
        if (data.entitlements_reviewed !== undefined) updatePayload.entitlements_reviewed = data.entitlements_reviewed;
        
        
        if (data.reviewer_decision !== undefined) updatePayload.reviewer_decision = data.reviewer_decision;
        
        
        if (data.justification !== undefined) updatePayload.justification = data.justification;
        
        
        if (data.action_required !== undefined) updatePayload.action_required = data.action_required;
        
        
        if (data.completed_at !== undefined) updatePayload.completed_at = data.completed_at;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        updatePayload.updatedById = currentUser.id;

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

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

        
        

        

        return access_review_items;
    }

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

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

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


        return access_review_items;
    }

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

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

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

        await access_review_items.destroy({
            transaction
        });

        return access_review_items;
    }

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

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

        if (!access_review_items) {
            return access_review_items;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.organization = await access_review_items.getOrganization({
            transaction
        });
        
        
        output.access_review = await access_review_items.getAccess_review({
            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',
        
      },

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



    ];

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

            
            if (filter.subject_display_name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'access_review_items',
                        'subject_display_name',
                        filter.subject_display_name,
                    ),
                };
            }
            
            if (filter.subject_identifier) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'access_review_items',
                        'subject_identifier',
                        filter.subject_identifier,
                    ),
                };
            }
            
            if (filter.system_name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'access_review_items',
                        'system_name',
                        filter.system_name,
                    ),
                };
            }
            
            if (filter.entitlements_reviewed) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'access_review_items',
                        'entitlements_reviewed',
                        filter.entitlements_reviewed,
                    ),
                };
            }
            
            if (filter.justification) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'access_review_items',
                        'justification',
                        filter.justification,
                    ),
                };
            }
            

            
            

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

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

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

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

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


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

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

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

    
};

