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

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

        const tenants = await db.tenants.create(
            {
                id: data.id || undefined,
        
        name: data.name
        ||
        null
            ,
            
        subdomain: data.subdomain
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        tagline: data.tagline
        ||
        null
            ,
            
        primary_color: data.primary_color
        ||
        null
            ,
            
        secondary_color: data.secondary_color
        ||
        null
            ,
            
        default_language: data.default_language
        ||
        null
            ,
            
        primary_currency: data.primary_currency
        ||
        null
            ,
            
        secondary_currency: data.secondary_currency
        ||
        null
            ,
            
        sso_enabled: data.sso_enabled
        ||
        false
        
            ,
            
        suspended_on: data.suspended_on
        ||
        null
            ,
            
        data_retention_policy: data.data_retention_policy
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await tenants.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

        
        await FileDBApi.replaceRelationFiles(
            {
                belongsTo: db.tenants.getTableName(),
                belongsToColumn: 'logo',
                belongsToId: tenants.id,
            },
            data.logo,
            options,
        );
        

        return tenants;
    }
    

    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 tenantsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                name: item.name
            ||
            null
            ,
            
                subdomain: item.subdomain
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
                tagline: item.tagline
            ||
            null
            ,
            
                primary_color: item.primary_color
            ||
            null
            ,
            
                secondary_color: item.secondary_color
            ||
            null
            ,
            
                default_language: item.default_language
            ||
            null
            ,
            
                primary_currency: item.primary_currency
            ||
            null
            ,
            
                secondary_currency: item.secondary_currency
            ||
            null
            ,
            
                sso_enabled: item.sso_enabled
            ||
            false
        
            ,
            
                suspended_on: item.suspended_on
            ||
            null
            ,
            
                data_retention_policy: item.data_retention_policy
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        
        for (let i = 0; i < tenants.length; i++) {
            await FileDBApi.replaceRelationFiles(
                {
                    belongsTo: db.tenants.getTableName(),
                    belongsToColumn: 'logo',
                    belongsToId: tenants[i].id,
                },
                data[i].logo,
                options,
            );
        }
        

        return tenants;
    }

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


        

        const updatePayload = {};
        
        if (data.name !== undefined) updatePayload.name = data.name;
        
        
        if (data.subdomain !== undefined) updatePayload.subdomain = data.subdomain;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.tagline !== undefined) updatePayload.tagline = data.tagline;
        
        
        if (data.primary_color !== undefined) updatePayload.primary_color = data.primary_color;
        
        
        if (data.secondary_color !== undefined) updatePayload.secondary_color = data.secondary_color;
        
        
        if (data.default_language !== undefined) updatePayload.default_language = data.default_language;
        
        
        if (data.primary_currency !== undefined) updatePayload.primary_currency = data.primary_currency;
        
        
        if (data.secondary_currency !== undefined) updatePayload.secondary_currency = data.secondary_currency;
        
        
        if (data.sso_enabled !== undefined) updatePayload.sso_enabled = data.sso_enabled;
        
        
        if (data.suspended_on !== undefined) updatePayload.suspended_on = data.suspended_on;
        
        
        if (data.data_retention_policy !== undefined) updatePayload.data_retention_policy = data.data_retention_policy;
        
        
        updatePayload.updatedById = currentUser.id;

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

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

        
        

        
        await FileDBApi.replaceRelationFiles(
            {
                belongsTo: db.tenants.getTableName(),
                belongsToColumn: 'logo',
                belongsToId: tenants.id,
            },
            data.logo,
            options,
        );
        

        return tenants;
    }

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

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

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


        return tenants;
    }

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

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

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

        await tenants.destroy({
            transaction
        });

        return tenants;
    }

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

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

        if (!tenants) {
            return tenants;
        }

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

        
        
        
        
        
        
        output.departments_tenant = await tenants.getDepartments_tenant({
            transaction
        });
        
        
        output.projects_tenant = await tenants.getProjects_tenant({
            transaction
        });
        
        
        output.budget_lines_tenant = await tenants.getBudget_lines_tenant({
            transaction
        });
        
        
        output.workflow_rules_tenant = await tenants.getWorkflow_rules_tenant({
            transaction
        });
        
        
        output.currency_rates_tenant = await tenants.getCurrency_rates_tenant({
            transaction
        });
        
        
        output.requisitions_tenant = await tenants.getRequisitions_tenant({
            transaction
        });
        
        
        output.approval_steps_tenant = await tenants.getApproval_steps_tenant({
            transaction
        });
        
        
        output.procurement_cases_tenant = await tenants.getProcurement_cases_tenant({
            transaction
        });
        
        
        output.suppliers_tenant = await tenants.getSuppliers_tenant({
            transaction
        });
        
        
        output.supplier_categories_tenant = await tenants.getSupplier_categories_tenant({
            transaction
        });
        
        
        output.supplier_diligence_checks_tenant = await tenants.getSupplier_diligence_checks_tenant({
            transaction
        });
        
        
        output.tender_events_tenant = await tenants.getTender_events_tenant({
            transaction
        });
        
        
        output.supplier_offers_tenant = await tenants.getSupplier_offers_tenant({
            transaction
        });
        
        
        output.bid_criteria_tenant = await tenants.getBid_criteria_tenant({
            transaction
        });
        
        
        output.offer_scores_tenant = await tenants.getOffer_scores_tenant({
            transaction
        });
        
        
        output.awards_tenant = await tenants.getAwards_tenant({
            transaction
        });
        
        
        output.purchase_orders_tenant = await tenants.getPurchase_orders_tenant({
            transaction
        });
        
        
        output.po_lines_tenant = await tenants.getPo_lines_tenant({
            transaction
        });
        
        
        output.goods_receipt_notes_tenant = await tenants.getGoods_receipt_notes_tenant({
            transaction
        });
        
        
        output.grn_lines_tenant = await tenants.getGrn_lines_tenant({
            transaction
        });
        
        
        output.service_acceptance_notes_tenant = await tenants.getService_acceptance_notes_tenant({
            transaction
        });
        
        
        output.discrepancy_cases_tenant = await tenants.getDiscrepancy_cases_tenant({
            transaction
        });
        
        
        output.archive_items_tenant = await tenants.getArchive_items_tenant({
            transaction
        });
        
        
        output.access_logs_tenant = await tenants.getAccess_logs_tenant({
            transaction
        });
        
        
        output.notifications_tenant = await tenants.getNotifications_tenant({
            transaction
        });
        
        
        output.audit_events_tenant = await tenants.getAudit_events_tenant({
            transaction
        });
        
        
        output.export_jobs_tenant = await tenants.getExport_jobs_tenant({
            transaction
        });
        
        
        output.sessions_tenant = await tenants.getSessions_tenant({
            transaction
        });
        
        
        
        output.logo = await tenants.getLogo({
            transaction
        });
        
        
        output.organizations = await tenants.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.organizations,
        as: 'organizations',
        
      },



      {
        model: db.file,
        as: 'logo',
      },

    ];

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

            
            if (filter.name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'tenants',
                        'name',
                        filter.name,
                    ),
                };
            }
            
            if (filter.subdomain) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'tenants',
                        'subdomain',
                        filter.subdomain,
                    ),
                };
            }
            
            if (filter.tagline) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'tenants',
                        'tagline',
                        filter.tagline,
                    ),
                };
            }
            
            if (filter.primary_color) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'tenants',
                        'primary_color',
                        filter.primary_color,
                    ),
                };
            }
            
            if (filter.secondary_color) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'tenants',
                        'secondary_color',
                        filter.secondary_color,
                    ),
                };
            }
            
            if (filter.data_retention_policy) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'tenants',
                        'data_retention_policy',
                        filter.data_retention_policy,
                    ),
                };
            }
            

            
            

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

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    suspended_on: {
                    ...where.suspended_on,
                            [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.default_language) {
                where = {
                    ...where,
                default_language: filter.default_language,
            };
            }
            
            if (filter.primary_currency) {
                where = {
                    ...where,
                primary_currency: filter.primary_currency,
            };
            }
            
            if (filter.secondary_currency) {
                where = {
                    ...where,
                secondary_currency: filter.secondary_currency,
            };
            }
            
            if (filter.sso_enabled) {
                where = {
                    ...where,
                sso_enabled: filter.sso_enabled,
            };
            }
            


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

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

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

    
};

