
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
            ,
            
        timezone: data.timezone
        ||
        null
            ,
            
        default_currency: data.default_currency
        ||
        null
            ,
            
        is_active: data.is_active
        ||
        false
        
            ,
            
        billing_email: data.billing_email
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

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

        
        await tenants.setMemberships(data.memberships || [], {
            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
            ,
            
                timezone: item.timezone
            ||
            null
            ,
            
                default_currency: item.default_currency
            ||
            null
            ,
            
                is_active: item.is_active
            ||
            false
        
            ,
            
                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.timezone !== undefined) updatePayload.timezone = data.timezone;
        
        
        if (data.default_currency !== undefined) updatePayload.default_currency = data.default_currency;
        
        
        if (data.is_active !== undefined) updatePayload.is_active = data.is_active;
        
        
        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 }
            );
        }
        

        
        
        if (data.memberships !== undefined) {
            await tenants.setMemberships(data.memberships, { 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.memberships_tenant = await tenants.getMemberships_tenant({
            transaction
        });
        
        
        
        output.approval_workflows_tenant = await tenants.getApproval_workflows_tenant({
            transaction
        });
        
        
        
        output.approval_requests_tenant = await tenants.getApproval_requests_tenant({
            transaction
        });
        
        
        
        output.companies_tenant = await tenants.getCompanies_tenant({
            transaction
        });
        
        
        output.customers_tenant = await tenants.getCustomers_tenant({
            transaction
        });
        
        
        output.suppliers_tenant = await tenants.getSuppliers_tenant({
            transaction
        });
        
        
        output.uoms_tenant = await tenants.getUoms_tenant({
            transaction
        });
        
        
        output.item_categories_tenant = await tenants.getItem_categories_tenant({
            transaction
        });
        
        
        output.items_tenant = await tenants.getItems_tenant({
            transaction
        });
        
        
        output.warehouses_tenant = await tenants.getWarehouses_tenant({
            transaction
        });
        
        
        
        output.lots_tenant = await tenants.getLots_tenant({
            transaction
        });
        
        
        output.serial_numbers_tenant = await tenants.getSerial_numbers_tenant({
            transaction
        });
        
        
        output.inventory_transfers_tenant = await tenants.getInventory_transfers_tenant({
            transaction
        });
        
        
        
        output.stock_movements_tenant = await tenants.getStock_movements_tenant({
            transaction
        });
        
        
        output.quotations_tenant = await tenants.getQuotations_tenant({
            transaction
        });
        
        
        
        output.sales_orders_tenant = await tenants.getSales_orders_tenant({
            transaction
        });
        
        
        
        
        output.invoices_tenant = await tenants.getInvoices_tenant({
            transaction
        });
        
        
        
        output.customer_returns_tenant = await tenants.getCustomer_returns_tenant({
            transaction
        });
        
        
        
        output.purchase_orders_tenant = await tenants.getPurchase_orders_tenant({
            transaction
        });
        
        
        
        output.receipts_tenant = await tenants.getReceipts_tenant({
            transaction
        });
        
        
        
        output.vendor_bills_tenant = await tenants.getVendor_bills_tenant({
            transaction
        });
        
        
        
        output.chart_of_accounts_tenant = await tenants.getChart_of_accounts_tenant({
            transaction
        });
        
        
        output.fiscal_periods_tenant = await tenants.getFiscal_periods_tenant({
            transaction
        });
        
        
        output.journal_entries_tenant = await tenants.getJournal_entries_tenant({
            transaction
        });
        
        
        
        output.payments_tenant = await tenants.getPayments_tenant({
            transaction
        });
        
        
        output.tax_rates_tenant = await tenants.getTax_rates_tenant({
            transaction
        });
        
        
        output.webhooks_tenant = await tenants.getWebhooks_tenant({
            transaction
        });
        
        
        
        output.webhook_deliveries_tenant = await tenants.getWebhook_deliveries_tenant({
            transaction
        });
        
        
        output.email_notifications_tenant = await tenants.getEmail_notifications_tenant({
            transaction
        });
        
        
        output.csv_import_jobs_tenant = await tenants.getCsv_import_jobs_tenant({
            transaction
        });
        
        
        output.reports_tenant = await tenants.getReports_tenant({
            transaction
        });
        
        
        output.dashboards_tenant = await tenants.getDashboards_tenant({
            transaction
        });
        
        
        
        
        output.memberships = await tenants.getMemberships({
            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.memberships,
        as: 'memberships',
        required: false,
      },


    ];

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

            
            

            

            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.memberships) {
        const searchTerms = filter.memberships.split('|');

        include = [
          {
            model: db.memberships,
            as: 'memberships_filter',
            required: searchTerms.length > 0,
            where: searchTerms.length > 0 ? {
              [Op.or]: [
                { id: { [Op.in]: searchTerms.map(term => Utils.uuid(term)) } },
                { 
                  status: {
                    [Op.or]: searchTerms.map(term => ({ [Op.iLike]: `%${term}%` }))
                  }
                }
              ]
            } : undefined
          },
          ...include,
        ]
      }


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

    
};

