
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
            ,
            
        slug: data.slug
        ||
        null
            ,
            
        primary_email: data.primary_email
        ||
        null
            ,
            
        primary_phone: data.primary_phone
        ||
        null
            ,
            
        time_zone: data.time_zone
        ||
        null
            ,
            
        currency_code: data.currency_code
        ||
        null
            ,
            
        is_active: data.is_active
        ||
        false
        
            ,
            
            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
            ,
            
                slug: item.slug
            ||
            null
            ,
            
                primary_email: item.primary_email
            ||
            null
            ,
            
                primary_phone: item.primary_phone
            ||
            null
            ,
            
                time_zone: item.time_zone
            ||
            null
            ,
            
                currency_code: item.currency_code
            ||
            null
            ,
            
                is_active: item.is_active
            ||
            false
        
            ,
            
            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.slug !== undefined) updatePayload.slug = data.slug;
        
        
        if (data.primary_email !== undefined) updatePayload.primary_email = data.primary_email;
        
        
        if (data.primary_phone !== undefined) updatePayload.primary_phone = data.primary_phone;
        
        
        if (data.time_zone !== undefined) updatePayload.time_zone = data.time_zone;
        
        
        if (data.currency_code !== undefined) updatePayload.currency_code = data.currency_code;
        
        
        if (data.is_active !== undefined) updatePayload.is_active = data.is_active;
        
        
        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.locations_tenant = await tenants.getLocations_tenant({
            transaction
        });
        
        
        
        output.tenant_memberships_tenant = await tenants.getTenant_memberships_tenant({
            transaction
        });
        
        
        output.customers_tenant = await tenants.getCustomers_tenant({
            transaction
        });
        
        
        output.products_tenant = await tenants.getProducts_tenant({
            transaction
        });
        
        
        
        output.tax_rates_tenant = await tenants.getTax_rates_tenant({
            transaction
        });
        
        
        output.discounts_tenant = await tenants.getDiscounts_tenant({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.tenant_partnerships_tenant = await tenants.getTenant_partnerships_tenant({
            transaction
        });
        
        
        
        output.helcim_configurations_tenant = await tenants.getHelcim_configurations_tenant({
            transaction
        });
        
        
        output.reports_tenant = await tenants.getReports_tenant({
            transaction
        });
        
        
        output.audit_events_tenant = await tenants.getAudit_events_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.slug) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'tenants',
                        'slug',
                        filter.slug,
                    ),
                };
            }
            
            if (filter.primary_email) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'tenants',
                        'primary_email',
                        filter.primary_email,
                    ),
                };
            }
            
            if (filter.primary_phone) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'tenants',
                        'primary_phone',
                        filter.primary_phone,
                    ),
                };
            }
            
            if (filter.time_zone) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'tenants',
                        'time_zone',
                        filter.time_zone,
                    ),
                };
            }
            
            if (filter.currency_code) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'tenants',
                        'currency_code',
                        filter.currency_code,
                    ),
                };
            }
            

            
            

            

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

    
};

