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

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

        const compliance_templates = await db.compliance_templates.create(
            {
                id: data.id || undefined,
        
        template_name: data.template_name
        ||
        null
            ,
            
        code: data.code
        ||
        null
            ,
            
        frequency: data.frequency
        ||
        null
            ,
            
        due_day_of_month: data.due_day_of_month
        ||
        null
            ,
            
        due_month_of_year: data.due_month_of_year
        ||
        null
            ,
            
        grace_days: data.grace_days
        ||
        null
            ,
            
        applies_to_business_type: data.applies_to_business_type
        ||
        null
            ,
            
        applies_to_industry: data.applies_to_industry
        ||
        null
            ,
            
        applies_to_state: data.applies_to_state
        ||
        null
            ,
            
        min_employee_count: data.min_employee_count
        ||
        null
            ,
            
        max_employee_count: data.max_employee_count
        ||
        null
            ,
            
        risk_level: data.risk_level
        ||
        null
            ,
            
        legal_reference: data.legal_reference
        ||
        null
            ,
            
        instructions: data.instructions
        ||
        null
            ,
            
        is_active: data.is_active
        ||
        false
        
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await compliance_templates.setCategory( data.category || null, {
            transaction,
        });
        
        await compliance_templates.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

        

        return compliance_templates;
    }
    

    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 compliance_templatesData = data.map((item, index) => ({
                id: item.id || undefined,
                
                template_name: item.template_name
            ||
            null
            ,
            
                code: item.code
            ||
            null
            ,
            
                frequency: item.frequency
            ||
            null
            ,
            
                due_day_of_month: item.due_day_of_month
            ||
            null
            ,
            
                due_month_of_year: item.due_month_of_year
            ||
            null
            ,
            
                grace_days: item.grace_days
            ||
            null
            ,
            
                applies_to_business_type: item.applies_to_business_type
            ||
            null
            ,
            
                applies_to_industry: item.applies_to_industry
            ||
            null
            ,
            
                applies_to_state: item.applies_to_state
            ||
            null
            ,
            
                min_employee_count: item.min_employee_count
            ||
            null
            ,
            
                max_employee_count: item.max_employee_count
            ||
            null
            ,
            
                risk_level: item.risk_level
            ||
            null
            ,
            
                legal_reference: item.legal_reference
            ||
            null
            ,
            
                instructions: item.instructions
            ||
            null
            ,
            
                is_active: item.is_active
            ||
            false
        
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return compliance_templates;
    }

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


        

        const updatePayload = {};
        
        if (data.template_name !== undefined) updatePayload.template_name = data.template_name;
        
        
        if (data.code !== undefined) updatePayload.code = data.code;
        
        
        if (data.frequency !== undefined) updatePayload.frequency = data.frequency;
        
        
        if (data.due_day_of_month !== undefined) updatePayload.due_day_of_month = data.due_day_of_month;
        
        
        if (data.due_month_of_year !== undefined) updatePayload.due_month_of_year = data.due_month_of_year;
        
        
        if (data.grace_days !== undefined) updatePayload.grace_days = data.grace_days;
        
        
        if (data.applies_to_business_type !== undefined) updatePayload.applies_to_business_type = data.applies_to_business_type;
        
        
        if (data.applies_to_industry !== undefined) updatePayload.applies_to_industry = data.applies_to_industry;
        
        
        if (data.applies_to_state !== undefined) updatePayload.applies_to_state = data.applies_to_state;
        
        
        if (data.min_employee_count !== undefined) updatePayload.min_employee_count = data.min_employee_count;
        
        
        if (data.max_employee_count !== undefined) updatePayload.max_employee_count = data.max_employee_count;
        
        
        if (data.risk_level !== undefined) updatePayload.risk_level = data.risk_level;
        
        
        if (data.legal_reference !== undefined) updatePayload.legal_reference = data.legal_reference;
        
        
        if (data.instructions !== undefined) updatePayload.instructions = data.instructions;
        
        
        if (data.is_active !== undefined) updatePayload.is_active = data.is_active;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.category !== undefined) {
            await compliance_templates.setCategory(
              
              data.category,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await compliance_templates.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        

        

        return compliance_templates;
    }

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

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

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


        return compliance_templates;
    }

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

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

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

        await compliance_templates.destroy({
            transaction
        });

        return compliance_templates;
    }

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

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

        if (!compliance_templates) {
            return compliance_templates;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        output.company_compliances_template = await compliance_templates.getCompany_compliances_template({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.compliance_rule_overrides_template = await compliance_templates.getCompliance_rule_overrides_template({
            transaction
        });
        
        
        
        
        
        output.category = await compliance_templates.getCategory({
            transaction
        });
        
        
        output.organizations = await compliance_templates.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.compliance_categories,
        as: 'category',
        
        where: filter.category ? {
          [Op.or]: [
            { id: { [Op.in]: filter.category.split('|').map(term => Utils.uuid(term)) } },
            {
              category_name: {
                [Op.or]: filter.category.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.template_name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'compliance_templates',
                        'template_name',
                        filter.template_name,
                    ),
                };
            }
            
            if (filter.code) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'compliance_templates',
                        'code',
                        filter.code,
                    ),
                };
            }
            
            if (filter.applies_to_industry) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'compliance_templates',
                        'applies_to_industry',
                        filter.applies_to_industry,
                    ),
                };
            }
            
            if (filter.legal_reference) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'compliance_templates',
                        'legal_reference',
                        filter.legal_reference,
                    ),
                };
            }
            
            if (filter.instructions) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'compliance_templates',
                        'instructions',
                        filter.instructions,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

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

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

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

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

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

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

            
            if (filter.frequency) {
                where = {
                    ...where,
                frequency: filter.frequency,
            };
            }
            
            if (filter.applies_to_business_type) {
                where = {
                    ...where,
                applies_to_business_type: filter.applies_to_business_type,
            };
            }
            
            if (filter.applies_to_state) {
                where = {
                    ...where,
                applies_to_state: filter.applies_to_state,
            };
            }
            
            if (filter.risk_level) {
                where = {
                    ...where,
                risk_level: filter.risk_level,
            };
            }
            
            if (filter.is_active) {
                where = {
                    ...where,
                is_active: filter.is_active,
            };
            }
            


      

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

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

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

    
};

