
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,
        
        tenant_name: data.tenant_name
        ||
        null
            ,
            
        legal_name: data.legal_name
        ||
        null
            ,
            
        domain: data.domain
        ||
        null
            ,
            
        industry: data.industry
        ||
        null
            ,
            
        default_currency: data.default_currency
        ||
        null
            ,
            
        timezone: data.timezone
        ||
        null
            ,
            
        is_active: data.is_active
        ||
        false
        
            ,
            
        support_email: data.support_email
        ||
        null
            ,
            
        support_phone: data.support_phone
        ||
        null
            ,
            
        address: data.address
        ||
        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_images',
                belongsToId: tenants.id,
            },
            data.logo_images,
            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,
                
                tenant_name: item.tenant_name
            ||
            null
            ,
            
                legal_name: item.legal_name
            ||
            null
            ,
            
                domain: item.domain
            ||
            null
            ,
            
                industry: item.industry
            ||
            null
            ,
            
                default_currency: item.default_currency
            ||
            null
            ,
            
                timezone: item.timezone
            ||
            null
            ,
            
                is_active: item.is_active
            ||
            false
        
            ,
            
                support_email: item.support_email
            ||
            null
            ,
            
                support_phone: item.support_phone
            ||
            null
            ,
            
                address: item.address
            ||
            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_images',
                    belongsToId: tenants[i].id,
                },
                data[i].logo_images,
                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.tenant_name !== undefined) updatePayload.tenant_name = data.tenant_name;
        
        
        if (data.legal_name !== undefined) updatePayload.legal_name = data.legal_name;
        
        
        if (data.domain !== undefined) updatePayload.domain = data.domain;
        
        
        if (data.industry !== undefined) updatePayload.industry = data.industry;
        
        
        if (data.default_currency !== undefined) updatePayload.default_currency = data.default_currency;
        
        
        if (data.timezone !== undefined) updatePayload.timezone = data.timezone;
        
        
        if (data.is_active !== undefined) updatePayload.is_active = data.is_active;
        
        
        if (data.support_email !== undefined) updatePayload.support_email = data.support_email;
        
        
        if (data.support_phone !== undefined) updatePayload.support_phone = data.support_phone;
        
        
        if (data.address !== undefined) updatePayload.address = data.address;
        
        
        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_images',
                belongsToId: tenants.id,
            },
            data.logo_images,
            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.products_tenant = await tenants.getProducts_tenant({
            transaction
        });
        
        
        output.warehouses_tenant = await tenants.getWarehouses_tenant({
            transaction
        });
        
        
        output.inventory_items_tenant = await tenants.getInventory_items_tenant({
            transaction
        });
        
        
        output.inventory_movements_tenant = await tenants.getInventory_movements_tenant({
            transaction
        });
        
        
        output.customers_tenant = await tenants.getCustomers_tenant({
            transaction
        });
        
        
        output.orders_tenant = await tenants.getOrders_tenant({
            transaction
        });
        
        
        
        output.invoices_tenant = await tenants.getInvoices_tenant({
            transaction
        });
        
        
        output.payments_tenant = await tenants.getPayments_tenant({
            transaction
        });
        
        
        output.commission_plans_tenant = await tenants.getCommission_plans_tenant({
            transaction
        });
        
        
        
        output.commissions_tenant = await tenants.getCommissions_tenant({
            transaction
        });
        
        
        output.payouts_tenant = await tenants.getPayouts_tenant({
            transaction
        });
        
        
        output.bonus_programs_tenant = await tenants.getBonus_programs_tenant({
            transaction
        });
        
        
        output.referral_links_tenant = await tenants.getReferral_links_tenant({
            transaction
        });
        
        
        output.reseller_stores_tenant = await tenants.getReseller_stores_tenant({
            transaction
        });
        
        
        
        output.notifications_tenant = await tenants.getNotifications_tenant({
            transaction
        });
        
        
        output.ai_insights_tenant = await tenants.getAi_insights_tenant({
            transaction
        });
        
        
        output.sales_targets_tenant = await tenants.getSales_targets_tenant({
            transaction
        });
        
        
        
        output.logo_images = await tenants.getLogo_images({
            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_images',
      },

    ];

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

            
            if (filter.tenant_name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'tenants',
                        'tenant_name',
                        filter.tenant_name,
                    ),
                };
            }
            
            if (filter.legal_name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'tenants',
                        'legal_name',
                        filter.legal_name,
                    ),
                };
            }
            
            if (filter.domain) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'tenants',
                        'domain',
                        filter.domain,
                    ),
                };
            }
            
            if (filter.industry) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'tenants',
                        'industry',
                        filter.industry,
                    ),
                };
            }
            
            if (filter.default_currency) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'tenants',
                        'default_currency',
                        filter.default_currency,
                    ),
                };
            }
            
            if (filter.timezone) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'tenants',
                        'timezone',
                        filter.timezone,
                    ),
                };
            }
            
            if (filter.support_email) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'tenants',
                        'support_email',
                        filter.support_email,
                    ),
                };
            }
            
            if (filter.support_phone) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'tenants',
                        'support_phone',
                        filter.support_phone,
                    ),
                };
            }
            
            if (filter.address) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'tenants',
                        'address',
                        filter.address,
                    ),
                };
            }
            

            
            

            

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

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

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

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

    
};

