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

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

        const access_reviews = await db.access_reviews.create(
            {
                id: data.id || undefined,
        
        review_name: data.review_name
        ||
        null
            ,
            
        review_scope: data.review_scope
        ||
        null
            ,
            
        review_type: data.review_type
        ||
        null
            ,
            
        start_date: data.start_date
        ||
        null
            ,
            
        due_date: data.due_date
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        completion_percentage: data.completion_percentage
        ||
        null
            ,
            
        notes: data.notes
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await access_reviews.setOrganization(currentUser.organization.id || null, {
            transaction,
        });
        
        await access_reviews.setReviewer_user( data.reviewer_user || null, {
            transaction,
        });
        

        

        

        return access_reviews;
    }
    

    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_reviewsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                review_name: item.review_name
            ||
            null
            ,
            
                review_scope: item.review_scope
            ||
            null
            ,
            
                review_type: item.review_type
            ||
            null
            ,
            
                start_date: item.start_date
            ||
            null
            ,
            
                due_date: item.due_date
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
                completion_percentage: item.completion_percentage
            ||
            null
            ,
            
                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 access_reviews = await db.access_reviews.bulkCreate(access_reviewsData, { transaction });

        // For each item created, replace relation files
        

        return access_reviews;
    }

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


        

        const updatePayload = {};
        
        if (data.review_name !== undefined) updatePayload.review_name = data.review_name;
        
        
        if (data.review_scope !== undefined) updatePayload.review_scope = data.review_scope;
        
        
        if (data.review_type !== undefined) updatePayload.review_type = data.review_type;
        
        
        if (data.start_date !== undefined) updatePayload.start_date = data.start_date;
        
        
        if (data.due_date !== undefined) updatePayload.due_date = data.due_date;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.completion_percentage !== undefined) updatePayload.completion_percentage = data.completion_percentage;
        
        
        if (data.notes !== undefined) updatePayload.notes = data.notes;
        
        
        updatePayload.updatedById = currentUser.id;

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

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

        
        

        

        return access_reviews;
    }

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

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

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


        return access_reviews;
    }

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

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

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

        await access_reviews.destroy({
            transaction
        });

        return access_reviews;
    }

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

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

        if (!access_reviews) {
            return access_reviews;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.access_review_items_access_review = await access_reviews.getAccess_review_items_access_review({
            transaction
        });
        
        
        
        
        
        
        
        
        
        output.organization = await access_reviews.getOrganization({
            transaction
        });
        
        
        output.reviewer_user = await access_reviews.getReviewer_user({
            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.users,
        as: 'reviewer_user',
        
        where: filter.reviewer_user ? {
          [Op.or]: [
            { id: { [Op.in]: filter.reviewer_user.split('|').map(term => Utils.uuid(term)) } },
            {
              firstName: {
                [Op.or]: filter.reviewer_user.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },



    ];

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

            
            if (filter.review_name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'access_reviews',
                        'review_name',
                        filter.review_name,
                    ),
                };
            }
            
            if (filter.review_scope) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'access_reviews',
                        'review_scope',
                        filter.review_scope,
                    ),
                };
            }
            
            if (filter.notes) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'access_reviews',
                        'notes',
                        filter.notes,
                    ),
                };
            }
            

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

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

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

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

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

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

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

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

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

            
            if (filter.review_type) {
                where = {
                    ...where,
                review_type: filter.review_type,
            };
            }
            
            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_reviews.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_reviews',
                        'review_name',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

