
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
            ,
            
        slug: data.slug
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        trial_ends_at: data.trial_ends_at
        ||
        null
            ,
            
        timezone: data.timezone
        ||
        null
            ,
            
        default_currency: data.default_currency
        ||
        null
            ,
            
        primary_domain: data.primary_domain
        ||
        null
            ,
            
        logo_url: data.logo_url
        ||
        null
            ,
            
        billing_email: data.billing_email
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

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

        

        

        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
            ,
            
                slug: item.slug
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
                trial_ends_at: item.trial_ends_at
            ||
            null
            ,
            
                timezone: item.timezone
            ||
            null
            ,
            
                default_currency: item.default_currency
            ||
            null
            ,
            
                primary_domain: item.primary_domain
            ||
            null
            ,
            
                logo_url: item.logo_url
            ||
            null
            ,
            
                billing_email: item.billing_email
            ||
            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
        

        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.slug !== undefined) updatePayload.slug = data.slug;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.trial_ends_at !== undefined) updatePayload.trial_ends_at = data.trial_ends_at;
        
        
        if (data.timezone !== undefined) updatePayload.timezone = data.timezone;
        
        
        if (data.default_currency !== undefined) updatePayload.default_currency = data.default_currency;
        
        
        if (data.primary_domain !== undefined) updatePayload.primary_domain = data.primary_domain;
        
        
        if (data.logo_url !== undefined) updatePayload.logo_url = data.logo_url;
        
        
        if (data.billing_email !== undefined) updatePayload.billing_email = data.billing_email;
        
        
        updatePayload.updatedById = currentUser.id;

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

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

        
        

        

        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.pipelines_tenant = await tenants.getPipelines_tenant({
            transaction
        });
        
        
        
        output.companies_tenant = await tenants.getCompanies_tenant({
            transaction
        });
        
        
        output.contacts_tenant = await tenants.getContacts_tenant({
            transaction
        });
        
        
        output.leads_tenant = await tenants.getLeads_tenant({
            transaction
        });
        
        
        output.deals_tenant = await tenants.getDeals_tenant({
            transaction
        });
        
        
        output.activities_tenant = await tenants.getActivities_tenant({
            transaction
        });
        
        
        output.tasks_tenant = await tenants.getTasks_tenant({
            transaction
        });
        
        
        output.reminders_tenant = await tenants.getReminders_tenant({
            transaction
        });
        
        
        output.email_templates_tenant = await tenants.getEmail_templates_tenant({
            transaction
        });
        
        
        output.email_notifications_tenant = await tenants.getEmail_notifications_tenant({
            transaction
        });
        
        
        output.imports_tenant = await tenants.getImports_tenant({
            transaction
        });
        
        
        output.exports_tenant = await tenants.getExports_tenant({
            transaction
        });
        
        
        output.api_clients_tenant = await tenants.getApi_clients_tenant({
            transaction
        });
        
        
        output.api_tokens_tenant = await tenants.getApi_tokens_tenant({
            transaction
        });
        
        
        output.webhooks_tenant = await tenants.getWebhooks_tenant({
            transaction
        });
        
        
        output.webhook_deliveries_tenant = await tenants.getWebhook_deliveries_tenant({
            transaction
        });
        
        
        output.integrations_tenant = await tenants.getIntegrations_tenant({
            transaction
        });
        
        
        output.calendar_accounts_tenant = await tenants.getCalendar_accounts_tenant({
            transaction
        });
        
        
        output.calendar_events_tenant = await tenants.getCalendar_events_tenant({
            transaction
        });
        
        
        output.dashboard_widgets_tenant = await tenants.getDashboard_widgets_tenant({
            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',
        
      },



    ];

        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.slug) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'tenants',
                        'slug',
                        filter.slug,
                    ),
                };
            }
            
            if (filter.timezone) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'tenants',
                        'timezone',
                        filter.timezone,
                    ),
                };
            }
            
            if (filter.default_currency) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'tenants',
                        'default_currency',
                        filter.default_currency,
                    ),
                };
            }
            
            if (filter.primary_domain) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'tenants',
                        'primary_domain',
                        filter.primary_domain,
                    ),
                };
            }
            
            if (filter.logo_url) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'tenants',
                        'logo_url',
                        filter.logo_url,
                    ),
                };
            }
            
            if (filter.billing_email) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'tenants',
                        'billing_email',
                        filter.billing_email,
                    ),
                };
            }
            

            
            

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

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    trial_ends_at: {
                    ...where.trial_ends_at,
                            [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.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,
        }));
    }

    
};

