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

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

        const company_compliances = await db.company_compliances.create(
            {
                id: data.id || undefined,
        
        compliance_title: data.compliance_title
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        priority: data.priority
        ||
        null
            ,
            
        risk_level: data.risk_level
        ||
        null
            ,
            
        period_start_at: data.period_start_at
        ||
        null
            ,
            
        period_end_at: data.period_end_at
        ||
        null
            ,
            
        due_at: data.due_at
        ||
        null
            ,
            
        completed_at: data.completed_at
        ||
        null
            ,
            
        penalty_estimate: data.penalty_estimate
        ||
        null
            ,
            
        notes: data.notes
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await company_compliances.setCompany( data.company || null, {
            transaction,
        });
        
        await company_compliances.setTemplate( data.template || null, {
            transaction,
        });
        
        await company_compliances.setBranch( data.branch || null, {
            transaction,
        });
        
        await company_compliances.setDepartment( data.department || null, {
            transaction,
        });
        
        await company_compliances.setAssigned_to( data.assigned_to || null, {
            transaction,
        });
        
        await company_compliances.setCreated_by_user( data.created_by_user || null, {
            transaction,
        });
        
        await company_compliances.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

        

        return company_compliances;
    }
    

    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 company_compliancesData = data.map((item, index) => ({
                id: item.id || undefined,
                
                compliance_title: item.compliance_title
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
                priority: item.priority
            ||
            null
            ,
            
                risk_level: item.risk_level
            ||
            null
            ,
            
                period_start_at: item.period_start_at
            ||
            null
            ,
            
                period_end_at: item.period_end_at
            ||
            null
            ,
            
                due_at: item.due_at
            ||
            null
            ,
            
                completed_at: item.completed_at
            ||
            null
            ,
            
                penalty_estimate: item.penalty_estimate
            ||
            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 company_compliances = await db.company_compliances.bulkCreate(company_compliancesData, { transaction });

        // For each item created, replace relation files
        

        return company_compliances;
    }

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


        

        const updatePayload = {};
        
        if (data.compliance_title !== undefined) updatePayload.compliance_title = data.compliance_title;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.priority !== undefined) updatePayload.priority = data.priority;
        
        
        if (data.risk_level !== undefined) updatePayload.risk_level = data.risk_level;
        
        
        if (data.period_start_at !== undefined) updatePayload.period_start_at = data.period_start_at;
        
        
        if (data.period_end_at !== undefined) updatePayload.period_end_at = data.period_end_at;
        
        
        if (data.due_at !== undefined) updatePayload.due_at = data.due_at;
        
        
        if (data.completed_at !== undefined) updatePayload.completed_at = data.completed_at;
        
        
        if (data.penalty_estimate !== undefined) updatePayload.penalty_estimate = data.penalty_estimate;
        
        
        if (data.notes !== undefined) updatePayload.notes = data.notes;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.company !== undefined) {
            await company_compliances.setCompany(
              
              data.company,
              
              { transaction }
            );
        }
        
        if (data.template !== undefined) {
            await company_compliances.setTemplate(
              
              data.template,
              
              { transaction }
            );
        }
        
        if (data.branch !== undefined) {
            await company_compliances.setBranch(
              
              data.branch,
              
              { transaction }
            );
        }
        
        if (data.department !== undefined) {
            await company_compliances.setDepartment(
              
              data.department,
              
              { transaction }
            );
        }
        
        if (data.assigned_to !== undefined) {
            await company_compliances.setAssigned_to(
              
              data.assigned_to,
              
              { transaction }
            );
        }
        
        if (data.created_by_user !== undefined) {
            await company_compliances.setCreated_by_user(
              
              data.created_by_user,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await company_compliances.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        

        

        return company_compliances;
    }

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

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

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


        return company_compliances;
    }

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

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

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

        await company_compliances.destroy({
            transaction
        });

        return company_compliances;
    }

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

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

        if (!company_compliances) {
            return company_compliances;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        output.tasks_related_compliance = await company_compliances.getTasks_related_compliance({
            transaction
        });
        
        
        output.documents_related_compliance = await company_compliances.getDocuments_related_compliance({
            transaction
        });
        
        
        
        output.alerts_related_compliance = await company_compliances.getAlerts_related_compliance({
            transaction
        });
        
        
        output.calendar_events_related_compliance = await company_compliances.getCalendar_events_related_compliance({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.company = await company_compliances.getCompany({
            transaction
        });
        
        
        output.template = await company_compliances.getTemplate({
            transaction
        });
        
        
        output.branch = await company_compliances.getBranch({
            transaction
        });
        
        
        output.department = await company_compliances.getDepartment({
            transaction
        });
        
        
        output.assigned_to = await company_compliances.getAssigned_to({
            transaction
        });
        
        
        output.created_by_user = await company_compliances.getCreated_by_user({
            transaction
        });
        
        
        output.organizations = await company_compliances.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.companies,
        as: 'company',
        
        where: filter.company ? {
          [Op.or]: [
            { id: { [Op.in]: filter.company.split('|').map(term => Utils.uuid(term)) } },
            {
              company_name: {
                [Op.or]: filter.company.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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

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

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

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

      {
        model: db.users,
        as: 'created_by_user',
        
        where: filter.created_by_user ? {
          [Op.or]: [
            { id: { [Op.in]: filter.created_by_user.split('|').map(term => Utils.uuid(term)) } },
            {
              firstName: {
                [Op.or]: filter.created_by_user.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.compliance_title) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'company_compliances',
                        'compliance_title',
                        filter.compliance_title,
                    ),
                };
            }
            
            if (filter.notes) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'company_compliances',
                        'notes',
                        filter.notes,
                    ),
                };
            }
            

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

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

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

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

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

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

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    due_at: {
                    ...where.due_at,
                            [Op.lte]: end,
                    },
                };
                }
            }
            
            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.penalty_estimateRange) {
                const [start, end] = filter.penalty_estimateRange;

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

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

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

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


      

      

      

      

      

      

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

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

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

    
};

