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

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

        const companies = await db.companies.create(
            {
                id: data.id || undefined,
        
        company_name: data.company_name
        ||
        null
            ,
            
        business_type: data.business_type
        ||
        null
            ,
            
        industry: data.industry
        ||
        null
            ,
            
        gst_number: data.gst_number
        ||
        null
            ,
            
        pan_number: data.pan_number
        ||
        null
            ,
            
        cin_number: data.cin_number
        ||
        null
            ,
            
        state: data.state
        ||
        null
            ,
            
        employee_count: data.employee_count
        ||
        null
            ,
            
        compliance_score: data.compliance_score
        ||
        null
            ,
            
        risk_score: data.risk_score
        ||
        null
            ,
            
        is_demo: data.is_demo
        ||
        false
        
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await companies.setOwner_user( data.owner_user || null, {
            transaction,
        });
        
        await companies.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

        

        return companies;
    }
    

    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 companiesData = data.map((item, index) => ({
                id: item.id || undefined,
                
                company_name: item.company_name
            ||
            null
            ,
            
                business_type: item.business_type
            ||
            null
            ,
            
                industry: item.industry
            ||
            null
            ,
            
                gst_number: item.gst_number
            ||
            null
            ,
            
                pan_number: item.pan_number
            ||
            null
            ,
            
                cin_number: item.cin_number
            ||
            null
            ,
            
                state: item.state
            ||
            null
            ,
            
                employee_count: item.employee_count
            ||
            null
            ,
            
                compliance_score: item.compliance_score
            ||
            null
            ,
            
                risk_score: item.risk_score
            ||
            null
            ,
            
                is_demo: item.is_demo
            ||
            false
        
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return companies;
    }

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


        

        const updatePayload = {};
        
        if (data.company_name !== undefined) updatePayload.company_name = data.company_name;
        
        
        if (data.business_type !== undefined) updatePayload.business_type = data.business_type;
        
        
        if (data.industry !== undefined) updatePayload.industry = data.industry;
        
        
        if (data.gst_number !== undefined) updatePayload.gst_number = data.gst_number;
        
        
        if (data.pan_number !== undefined) updatePayload.pan_number = data.pan_number;
        
        
        if (data.cin_number !== undefined) updatePayload.cin_number = data.cin_number;
        
        
        if (data.state !== undefined) updatePayload.state = data.state;
        
        
        if (data.employee_count !== undefined) updatePayload.employee_count = data.employee_count;
        
        
        if (data.compliance_score !== undefined) updatePayload.compliance_score = data.compliance_score;
        
        
        if (data.risk_score !== undefined) updatePayload.risk_score = data.risk_score;
        
        
        if (data.is_demo !== undefined) updatePayload.is_demo = data.is_demo;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.owner_user !== undefined) {
            await companies.setOwner_user(
              
              data.owner_user,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await companies.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        

        

        return companies;
    }

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

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

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


        return companies;
    }

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

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

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

        await companies.destroy({
            transaction
        });

        return companies;
    }

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

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

        if (!companies) {
            return companies;
        }

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

        
        
        
        
        
        
        output.company_memberships_company = await companies.getCompany_memberships_company({
            transaction
        });
        
        
        output.branches_company = await companies.getBranches_company({
            transaction
        });
        
        
        output.departments_company = await companies.getDepartments_company({
            transaction
        });
        
        
        
        
        output.company_compliances_company = await companies.getCompany_compliances_company({
            transaction
        });
        
        
        output.tasks_company = await companies.getTasks_company({
            transaction
        });
        
        
        output.documents_company = await companies.getDocuments_company({
            transaction
        });
        
        
        
        output.alerts_company = await companies.getAlerts_company({
            transaction
        });
        
        
        output.calendar_events_company = await companies.getCalendar_events_company({
            transaction
        });
        
        
        
        output.company_subscriptions_company = await companies.getCompany_subscriptions_company({
            transaction
        });
        
        
        output.payments_company = await companies.getPayments_company({
            transaction
        });
        
        
        output.ai_chat_sessions_company = await companies.getAi_chat_sessions_company({
            transaction
        });
        
        
        
        output.audit_logs_company = await companies.getAudit_logs_company({
            transaction
        });
        
        
        output.activity_events_company = await companies.getActivity_events_company({
            transaction
        });
        
        
        output.report_exports_company = await companies.getReport_exports_company({
            transaction
        });
        
        
        output.compliance_rule_overrides_company = await companies.getCompliance_rule_overrides_company({
            transaction
        });
        
        
        output.integrations_company = await companies.getIntegrations_company({
            transaction
        });
        
        
        output.notifications_preferences_company = await companies.getNotifications_preferences_company({
            transaction
        });
        
        
        
        output.owner_user = await companies.getOwner_user({
            transaction
        });
        
        
        output.organizations = await companies.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.users,
        as: 'owner_user',
        
        where: filter.owner_user ? {
          [Op.or]: [
            { id: { [Op.in]: filter.owner_user.split('|').map(term => Utils.uuid(term)) } },
            {
              firstName: {
                [Op.or]: filter.owner_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.company_name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'companies',
                        'company_name',
                        filter.company_name,
                    ),
                };
            }
            
            if (filter.industry) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'companies',
                        'industry',
                        filter.industry,
                    ),
                };
            }
            
            if (filter.gst_number) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'companies',
                        'gst_number',
                        filter.gst_number,
                    ),
                };
            }
            
            if (filter.pan_number) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'companies',
                        'pan_number',
                        filter.pan_number,
                    ),
                };
            }
            
            if (filter.cin_number) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'companies',
                        'cin_number',
                        filter.cin_number,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

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

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

            
            if (filter.business_type) {
                where = {
                    ...where,
                business_type: filter.business_type,
            };
            }
            
            if (filter.state) {
                where = {
                    ...where,
                state: filter.state,
            };
            }
            
            if (filter.is_demo) {
                where = {
                    ...where,
                is_demo: filter.is_demo,
            };
            }
            


      

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

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

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

    
};

