
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
            ,
            
        slug: data.slug
        ||
        null
            ,
            
        tenant_type: data.tenant_type
        ||
        null
            ,
            
        contact_email: data.contact_email
        ||
        null
            ,
            
        contact_phone: data.contact_phone
        ||
        null
            ,
            
        billing_address: data.billing_address
        ||
        null
            ,
            
        subscription_status: data.subscription_status
        ||
        null
            ,
            
        trial_ends_at: data.trial_ends_at
        ||
        null
            ,
            
        is_enabled: data.is_enabled
        ||
        false
        
            ,
            
            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,
                
                tenant_name: item.tenant_name
            ||
            null
            ,
            
                slug: item.slug
            ||
            null
            ,
            
                tenant_type: item.tenant_type
            ||
            null
            ,
            
                contact_email: item.contact_email
            ||
            null
            ,
            
                contact_phone: item.contact_phone
            ||
            null
            ,
            
                billing_address: item.billing_address
            ||
            null
            ,
            
                subscription_status: item.subscription_status
            ||
            null
            ,
            
                trial_ends_at: item.trial_ends_at
            ||
            null
            ,
            
                is_enabled: item.is_enabled
            ||
            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
        

        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.slug !== undefined) updatePayload.slug = data.slug;
        
        
        if (data.tenant_type !== undefined) updatePayload.tenant_type = data.tenant_type;
        
        
        if (data.contact_email !== undefined) updatePayload.contact_email = data.contact_email;
        
        
        if (data.contact_phone !== undefined) updatePayload.contact_phone = data.contact_phone;
        
        
        if (data.billing_address !== undefined) updatePayload.billing_address = data.billing_address;
        
        
        if (data.subscription_status !== undefined) updatePayload.subscription_status = data.subscription_status;
        
        
        if (data.trial_ends_at !== undefined) updatePayload.trial_ends_at = data.trial_ends_at;
        
        
        if (data.is_enabled !== undefined) updatePayload.is_enabled = data.is_enabled;
        
        
        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.user_memberships_tenant = await tenants.getUser_memberships_tenant({
            transaction
        });
        
        
        output.tenant_locations_tenant = await tenants.getTenant_locations_tenant({
            transaction
        });
        
        
        output.ponds_tenant = await tenants.getPonds_tenant({
            transaction
        });
        
        
        
        output.batches_tenant = await tenants.getBatches_tenant({
            transaction
        });
        
        
        output.feed_products_tenant = await tenants.getFeed_products_tenant({
            transaction
        });
        
        
        output.inventory_items_tenant = await tenants.getInventory_items_tenant({
            transaction
        });
        
        
        output.inventory_movements_tenant = await tenants.getInventory_movements_tenant({
            transaction
        });
        
        
        output.feeding_logs_tenant = await tenants.getFeeding_logs_tenant({
            transaction
        });
        
        
        output.water_quality_logs_tenant = await tenants.getWater_quality_logs_tenant({
            transaction
        });
        
        
        output.health_events_tenant = await tenants.getHealth_events_tenant({
            transaction
        });
        
        
        output.harvests_tenant = await tenants.getHarvests_tenant({
            transaction
        });
        
        
        output.marketplace_listings_seller_tenant = await tenants.getMarketplace_listings_seller_tenant({
            transaction
        });
        
        
        output.orders_buyer_tenant = await tenants.getOrders_buyer_tenant({
            transaction
        });
        
        output.orders_seller_tenant = await tenants.getOrders_seller_tenant({
            transaction
        });
        
        
        
        output.payment_transactions_buyer_tenant = await tenants.getPayment_transactions_buyer_tenant({
            transaction
        });
        
        output.payment_transactions_seller_tenant = await tenants.getPayment_transactions_seller_tenant({
            transaction
        });
        
        
        
        output.investments_investor_tenant = await tenants.getInvestments_investor_tenant({
            transaction
        });
        
        output.investments_farm_tenant = await tenants.getInvestments_farm_tenant({
            transaction
        });
        
        
        output.api_keys_tenant = await tenants.getApi_keys_tenant({
            transaction
        });
        
        
        output.webhook_endpoints_tenant = await tenants.getWebhook_endpoints_tenant({
            transaction
        });
        
        
        
        output.email_notifications_tenant = await tenants.getEmail_notifications_tenant({
            transaction
        });
        
        
        output.audit_logs_tenant = await tenants.getAudit_logs_tenant({
            transaction
        });
        
        
        output.csv_jobs_tenant = await tenants.getCsv_jobs_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.tenant_name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'tenants',
                        'tenant_name',
                        filter.tenant_name,
                    ),
                };
            }
            
            if (filter.slug) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'tenants',
                        'slug',
                        filter.slug,
                    ),
                };
            }
            
            if (filter.contact_email) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'tenants',
                        'contact_email',
                        filter.contact_email,
                    ),
                };
            }
            
            if (filter.contact_phone) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'tenants',
                        'contact_phone',
                        filter.contact_phone,
                    ),
                };
            }
            
            if (filter.billing_address) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'tenants',
                        'billing_address',
                        filter.billing_address,
                    ),
                };
            }
            

            
            

            
            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.tenant_type) {
                where = {
                    ...where,
                tenant_type: filter.tenant_type,
            };
            }
            
            if (filter.subscription_status) {
                where = {
                    ...where,
                subscription_status: filter.subscription_status,
            };
            }
            
            if (filter.is_enabled) {
                where = {
                    ...where,
                is_enabled: filter.is_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',
                        '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,
        }));
    }

    
};

