
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 BusinessesDBApi {
    

    
    static async create(data, options) {
        const currentUser = (options && options.currentUser) || { id: null };
        const transaction = (options && options.transaction) || undefined;

        const businesses = await db.businesses.create(
            {
                id: data.id || undefined,
        
        legal_name: data.legal_name
        ||
        null
            ,
            
        trade_name: data.trade_name
        ||
        null
            ,
            
        national_id: data.national_id
        ||
        null
            ,
            
        economic_code: data.economic_code
        ||
        null
            ,
            
        registration_number: data.registration_number
        ||
        null
            ,
            
        phone: data.phone
        ||
        null
            ,
            
        address: data.address
        ||
        null
            ,
            
        is_active: data.is_active
        ||
        false
        
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        

        

        

        return businesses;
    }
    

    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 businessesData = data.map((item, index) => ({
                id: item.id || undefined,
                
                legal_name: item.legal_name
            ||
            null
            ,
            
                trade_name: item.trade_name
            ||
            null
            ,
            
                national_id: item.national_id
            ||
            null
            ,
            
                economic_code: item.economic_code
            ||
            null
            ,
            
                registration_number: item.registration_number
            ||
            null
            ,
            
                phone: item.phone
            ||
            null
            ,
            
                address: item.address
            ||
            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 businesses = await db.businesses.bulkCreate(businessesData, { transaction });

        // For each item created, replace relation files
        

        return businesses;
    }

    static async update(id, data,  options) {
        const currentUser = (options && options.currentUser) || {id: null};
        const transaction = (options && options.transaction) || undefined;
        

        const businesses = await db.businesses.findByPk(id, {}, {transaction});


        

        const updatePayload = {};
        
        if (data.legal_name !== undefined) updatePayload.legal_name = data.legal_name;
        
        
        if (data.trade_name !== undefined) updatePayload.trade_name = data.trade_name;
        
        
        if (data.national_id !== undefined) updatePayload.national_id = data.national_id;
        
        
        if (data.economic_code !== undefined) updatePayload.economic_code = data.economic_code;
        
        
        if (data.registration_number !== undefined) updatePayload.registration_number = data.registration_number;
        
        
        if (data.phone !== undefined) updatePayload.phone = data.phone;
        
        
        if (data.address !== undefined) updatePayload.address = data.address;
        
        
        if (data.is_active !== undefined) updatePayload.is_active = data.is_active;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        

        
        

        

        return businesses;
    }

    static async deleteByIds(ids, options) {
        const currentUser = (options && options.currentUser) || { id: null };
        const transaction = (options && options.transaction) || undefined;

        const businesses = await db.businesses.findAll({
            where: {
                id: {
                    [Op.in]: ids,
                },
            },
            transaction,
        });

        await db.sequelize.transaction(async (transaction) => {
            for (const record of businesses) {
                await record.update(
                    {deletedBy: currentUser.id},
                    {transaction}
                );
            }
            for (const record of businesses) {
                await record.destroy({transaction});
            }
        });


        return businesses;
    }

    static async remove(id, options) {
        const currentUser = (options && options.currentUser) || {id: null};
        const transaction = (options && options.transaction) || undefined;

        const businesses = await db.businesses.findByPk(id, options);

        await businesses.update({
            deletedBy: currentUser.id
        }, {
            transaction,
        });

        await businesses.destroy({
            transaction
        });

        return businesses;
    }

    static async findBy(where, options) {
        const transaction = (options && options.transaction) || undefined;

        const businesses = await db.businesses.findOne(
            { where },
            { transaction },
        );

        if (!businesses) {
            return businesses;
        }

        const output = businesses.get({plain: true});

        
        
        
        
        
        output.branches_business = await businesses.getBranches_business({
            transaction
        });
        
        
        output.fiscal_years_business = await businesses.getFiscal_years_business({
            transaction
        });
        
        
        output.user_role_assignments_business = await businesses.getUser_role_assignments_business({
            transaction
        });
        
        
        
        output.role_permissions_business = await businesses.getRole_permissions_business({
            transaction
        });
        
        
        output.app_settings_business = await businesses.getApp_settings_business({
            transaction
        });
        
        
        output.currencies_business = await businesses.getCurrencies_business({
            transaction
        });
        
        
        output.currency_rates_business = await businesses.getCurrency_rates_business({
            transaction
        });
        
        
        output.numbering_profiles_business = await businesses.getNumbering_profiles_business({
            transaction
        });
        
        
        output.widgets_business = await businesses.getWidgets_business({
            transaction
        });
        
        
        
        
        
        
        output.counterparties_business = await businesses.getCounterparties_business({
            transaction
        });
        
        
        output.cost_centers_business = await businesses.getCost_centers_business({
            transaction
        });
        
        
        output.projects_business = await businesses.getProjects_business({
            transaction
        });
        
        
        output.contracts_business = await businesses.getContracts_business({
            transaction
        });
        
        
        output.cash_boxes_business = await businesses.getCash_boxes_business({
            transaction
        });
        
        
        output.banks_business = await businesses.getBanks_business({
            transaction
        });
        
        
        output.bank_accounts_business = await businesses.getBank_accounts_business({
            transaction
        });
        
        
        output.letters_of_credit_business = await businesses.getLetters_of_credit_business({
            transaction
        });
        
        
        output.pos_terminals_business = await businesses.getPos_terminals_business({
            transaction
        });
        
        
        output.sales_item_groups_business = await businesses.getSales_item_groups_business({
            transaction
        });
        
        
        output.warehouse_item_groups_business = await businesses.getWarehouse_item_groups_business({
            transaction
        });
        
        
        output.customer_groups_business = await businesses.getCustomer_groups_business({
            transaction
        });
        
        
        output.analytic_dimensions_business = await businesses.getAnalytic_dimensions_business({
            transaction
        });
        
        
        output.accounts_business = await businesses.getAccounts_business({
            transaction
        });
        
        
        output.journal_voucher_types_business = await businesses.getJournal_voucher_types_business({
            transaction
        });
        
        
        output.journal_vouchers_business = await businesses.getJournal_vouchers_business({
            transaction
        });
        
        
        
        output.approval_workflows_business = await businesses.getApproval_workflows_business({
            transaction
        });
        
        
        
        
        output.year_end_operations_business = await businesses.getYear_end_operations_business({
            transaction
        });
        
        
        output.report_definitions_business = await businesses.getReport_definitions_business({
            transaction
        });
        
        
        
        output.chat_conversations_business = await businesses.getChat_conversations_business({
            transaction
        });
        
        
        
        
        output.form_alarms_business = await businesses.getForm_alarms_business({
            transaction
        });
        
        
        output.data_export_jobs_business = await businesses.getData_export_jobs_business({
            transaction
        });
        
        
        

        return output;
    }

    static async findAll(
          filter,
           options
        ) {
        const limit = filter.limit || 0;
        let offset = 0;
        let where = {};
        const currentPage = +filter.page;

        

        

        offset = currentPage * limit;

        const orderBy = null;

    const transaction = (options && options.transaction) || undefined;

    let include = [



    ];

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

            
            if (filter.legal_name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'businesses',
                        'legal_name',
                        filter.legal_name,
                    ),
                };
            }
            
            if (filter.trade_name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'businesses',
                        'trade_name',
                        filter.trade_name,
                    ),
                };
            }
            
            if (filter.national_id) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'businesses',
                        'national_id',
                        filter.national_id,
                    ),
                };
            }
            
            if (filter.economic_code) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'businesses',
                        'economic_code',
                        filter.economic_code,
                    ),
                };
            }
            
            if (filter.registration_number) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'businesses',
                        'registration_number',
                        filter.registration_number,
                    ),
                };
            }
            
            if (filter.phone) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'businesses',
                        'phone',
                        filter.phone,
                    ),
                };
            }
            
            if (filter.address) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'businesses',
                        '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.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,
                        },
                    };
                }
            }
        }
        

        

        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.businesses.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, ) {
        let where = {};
        
        

        if (query) {
            where = {
                [Op.or]: [
                    { ['id']: Utils.uuid(query) },
                    Utils.ilike(
                        'businesses',
                        'trade_name',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

