
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
            ,
            
        tagline: data.tagline
        ||
        null
            ,
            
        primary_color: data.primary_color
        ||
        null
            ,
            
        default_language: data.default_language
        ||
        null
            ,
            
        timezone: data.timezone
        ||
        null
            ,
            
        primary_currency: data.primary_currency
        ||
        null
            ,
            
        secondary_currencies: data.secondary_currencies
        ||
        null
            ,
            
        address: data.address
        ||
        null
            ,
            
        phone: data.phone
        ||
        null
            ,
            
        billing_email: data.billing_email
        ||
        null
            ,
            
        support_email: data.support_email
        ||
        null
            ,
            
        two_factor_required_for_admins: data.two_factor_required_for_admins
        ||
        false
        
            ,
            
        ip_whitelist_enabled: data.ip_whitelist_enabled
        ||
        false
        
            ,
            
        ip_whitelist: data.ip_whitelist
        ||
        null
            ,
            
        business_hours: data.business_hours
        ||
        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
            ,
            
                tagline: item.tagline
            ||
            null
            ,
            
                primary_color: item.primary_color
            ||
            null
            ,
            
                default_language: item.default_language
            ||
            null
            ,
            
                timezone: item.timezone
            ||
            null
            ,
            
                primary_currency: item.primary_currency
            ||
            null
            ,
            
                secondary_currencies: item.secondary_currencies
            ||
            null
            ,
            
                address: item.address
            ||
            null
            ,
            
                phone: item.phone
            ||
            null
            ,
            
                billing_email: item.billing_email
            ||
            null
            ,
            
                support_email: item.support_email
            ||
            null
            ,
            
                two_factor_required_for_admins: item.two_factor_required_for_admins
            ||
            false
        
            ,
            
                ip_whitelist_enabled: item.ip_whitelist_enabled
            ||
            false
        
            ,
            
                ip_whitelist: item.ip_whitelist
            ||
            null
            ,
            
                business_hours: item.business_hours
            ||
            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.tagline !== undefined) updatePayload.tagline = data.tagline;
        
        
        if (data.primary_color !== undefined) updatePayload.primary_color = data.primary_color;
        
        
        if (data.default_language !== undefined) updatePayload.default_language = data.default_language;
        
        
        if (data.timezone !== undefined) updatePayload.timezone = data.timezone;
        
        
        if (data.primary_currency !== undefined) updatePayload.primary_currency = data.primary_currency;
        
        
        if (data.secondary_currencies !== undefined) updatePayload.secondary_currencies = data.secondary_currencies;
        
        
        if (data.address !== undefined) updatePayload.address = data.address;
        
        
        if (data.phone !== undefined) updatePayload.phone = data.phone;
        
        
        if (data.billing_email !== undefined) updatePayload.billing_email = data.billing_email;
        
        
        if (data.support_email !== undefined) updatePayload.support_email = data.support_email;
        
        
        if (data.two_factor_required_for_admins !== undefined) updatePayload.two_factor_required_for_admins = data.two_factor_required_for_admins;
        
        
        if (data.ip_whitelist_enabled !== undefined) updatePayload.ip_whitelist_enabled = data.ip_whitelist_enabled;
        
        
        if (data.ip_whitelist !== undefined) updatePayload.ip_whitelist = data.ip_whitelist;
        
        
        if (data.business_hours !== undefined) updatePayload.business_hours = data.business_hours;
        
        
        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,
        });

        if (tenants.length !== ids.length) {
            const error = new Error('One or more items were not found in the current organization scope.');
            error.code = 404;
            throw error;
        }

        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);

        if (!tenants) {
            const error = new Error('Item not found in the current organization scope.');
            error.code = 404;
            throw error;
        }

        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.service_lines_tenant = await tenants.getService_lines_tenant({
            transaction
        });
        
        
        output.services_tenant = await tenants.getServices_tenant({
            transaction
        });
        
        
        output.companies_tenant = await tenants.getCompanies_tenant({
            transaction
        });
        
        
        output.contacts_tenant = await tenants.getContacts_tenant({
            transaction
        });
        
        
        output.tags_tenant = await tenants.getTags_tenant({
            transaction
        });
        
        
        output.pipelines_tenant = await tenants.getPipelines_tenant({
            transaction
        });
        
        
        output.deal_stages_tenant = await tenants.getDeal_stages_tenant({
            transaction
        });
        
        
        output.leads_tenant = await tenants.getLeads_tenant({
            transaction
        });
        
        
        output.deals_tenant = await tenants.getDeals_tenant({
            transaction
        });
        
        
        output.project_templates_tenant = await tenants.getProject_templates_tenant({
            transaction
        });
        
        
        output.projects_tenant = await tenants.getProjects_tenant({
            transaction
        });
        
        
        output.milestones_tenant = await tenants.getMilestones_tenant({
            transaction
        });
        
        
        output.tasks_tenant = await tenants.getTasks_tenant({
            transaction
        });
        
        
        output.task_dependencies_tenant = await tenants.getTask_dependencies_tenant({
            transaction
        });
        
        
        output.deliverables_tenant = await tenants.getDeliverables_tenant({
            transaction
        });
        
        
        output.project_risks_tenant = await tenants.getProject_risks_tenant({
            transaction
        });
        
        
        output.project_status_reports_tenant = await tenants.getProject_status_reports_tenant({
            transaction
        });
        
        
        output.skills_tenant = await tenants.getSkills_tenant({
            transaction
        });
        
        
        output.team_members_tenant = await tenants.getTeam_members_tenant({
            transaction
        });
        
        
        output.team_member_skills_tenant = await tenants.getTeam_member_skills_tenant({
            transaction
        });
        
        
        output.resource_allocations_tenant = await tenants.getResource_allocations_tenant({
            transaction
        });
        
        
        output.leave_requests_tenant = await tenants.getLeave_requests_tenant({
            transaction
        });
        
        
        output.public_holidays_tenant = await tenants.getPublic_holidays_tenant({
            transaction
        });
        
        
        output.timesheets_tenant = await tenants.getTimesheets_tenant({
            transaction
        });
        
        
        output.time_entries_tenant = await tenants.getTime_entries_tenant({
            transaction
        });
        
        
        output.products_tenant = await tenants.getProducts_tenant({
            transaction
        });
        
        
        output.contracts_tenant = await tenants.getContracts_tenant({
            transaction
        });
        
        
        output.invoices_tenant = await tenants.getInvoices_tenant({
            transaction
        });
        
        
        output.invoice_line_items_tenant = await tenants.getInvoice_line_items_tenant({
            transaction
        });
        
        
        output.payments_tenant = await tenants.getPayments_tenant({
            transaction
        });
        
        
        output.support_slas_tenant = await tenants.getSupport_slas_tenant({
            transaction
        });
        
        
        output.support_tickets_tenant = await tenants.getSupport_tickets_tenant({
            transaction
        });
        
        
        output.ticket_comments_tenant = await tenants.getTicket_comments_tenant({
            transaction
        });
        
        
        output.csat_surveys_tenant = await tenants.getCsat_surveys_tenant({
            transaction
        });
        
        
        output.email_templates_tenant = await tenants.getEmail_templates_tenant({
            transaction
        });
        
        
        output.notifications_tenant = await tenants.getNotifications_tenant({
            transaction
        });
        
        
        output.audit_logs_tenant = await tenants.getAudit_logs_tenant({
            transaction
        });
        
        
        output.imports_tenant = await tenants.getImports_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.timezone) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'tenants',
                        'timezone',
                        filter.timezone,
                    ),
                };
            }
            
            if (filter.secondary_currencies) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'tenants',
                        'secondary_currencies',
                        filter.secondary_currencies,
                    ),
                };
            }
            
            if (filter.address) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'tenants',
                        'address',
                        filter.address,
                    ),
                };
            }
            
            if (filter.phone) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'tenants',
                        'phone',
                        filter.phone,
                    ),
                };
            }
            
            if (filter.billing_email) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'tenants',
                        'billing_email',
                        filter.billing_email,
                    ),
                };
            }
            
            if (filter.support_email) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'tenants',
                        'support_email',
                        filter.support_email,
                    ),
                };
            }
            
            if (filter.ip_whitelist) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'tenants',
                        'ip_whitelist',
                        filter.ip_whitelist,
                    ),
                };
            }
            
            if (filter.business_hours) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'tenants',
                        'business_hours',
                        filter.business_hours,
                    ),
                };
            }
            

            
            

            

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

            
            if (filter.default_language) {
                where = {
                    ...where,
                default_language: filter.default_language,
            };
            }
            
            if (filter.primary_currency) {
                where = {
                    ...where,
                primary_currency: filter.primary_currency,
            };
            }
            
            if (filter.two_factor_required_for_admins) {
                where = {
                    ...where,
                two_factor_required_for_admins: filter.two_factor_required_for_admins,
            };
            }
            
            if (filter.ip_whitelist_enabled) {
                where = {
                    ...where,
                ip_whitelist_enabled: filter.ip_whitelist_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.organizationsId = 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,
        }));
    }

    
};

