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

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

        const company_bank_accounts = await db.company_bank_accounts.create(
            {
                id: data.id || undefined,
        
        type: data.type
        ||
        null
            ,
            
        currency: data.currency
        ||
        null
            ,
            
        bank_name: data.bank_name
        ||
        null
            ,
            
        iban: data.iban
        ||
        null
            ,
            
        bic: data.bic
        ||
        null
            ,
            
        account_holder: data.account_holder
        ||
        null
            ,
            
        is_default: data.is_default
        ||
        false
        
            ,
            
        is_active: data.is_active
        ||
        false
        
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await company_bank_accounts.setCompany( data.company || null, {
            transaction,
        });
        

        

        

        return company_bank_accounts;
    }
    

    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 company_bank_accountsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                type: item.type
            ||
            null
            ,
            
                currency: item.currency
            ||
            null
            ,
            
                bank_name: item.bank_name
            ||
            null
            ,
            
                iban: item.iban
            ||
            null
            ,
            
                bic: item.bic
            ||
            null
            ,
            
                account_holder: item.account_holder
            ||
            null
            ,
            
                is_default: item.is_default
            ||
            false
        
            ,
            
                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 company_bank_accounts = await db.company_bank_accounts.bulkCreate(company_bank_accountsData, { transaction });

        // For each item created, replace relation files
        

        return company_bank_accounts;
    }

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

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


        

        const updatePayload = {};
        
        if (data.type !== undefined) updatePayload.type = data.type;
        
        
        if (data.currency !== undefined) updatePayload.currency = data.currency;
        
        
        if (data.bank_name !== undefined) updatePayload.bank_name = data.bank_name;
        
        
        if (data.iban !== undefined) updatePayload.iban = data.iban;
        
        
        if (data.bic !== undefined) updatePayload.bic = data.bic;
        
        
        if (data.account_holder !== undefined) updatePayload.account_holder = data.account_holder;
        
        
        if (data.is_default !== undefined) updatePayload.is_default = data.is_default;
        
        
        if (data.is_active !== undefined) updatePayload.is_active = data.is_active;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.company !== undefined) {
            await company_bank_accounts.setCompany(
              
              data.company,
              
              { transaction }
            );
        }
        

        
        

        

        return company_bank_accounts;
    }

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

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

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


        return company_bank_accounts;
    }

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

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

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

        await company_bank_accounts.destroy({
            transaction
        });

        return company_bank_accounts;
    }

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

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

        if (!company_bank_accounts) {
            return company_bank_accounts;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.company = await company_bank_accounts.getCompany({
            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 = [

      {
        model: db.companies,
        as: 'company',
        
        where: filter.company ? {
          [Op.or]: [
            { id: { [Op.in]: filter.company.split('|').map(term => Utils.uuid(term)) } },
            {
              name: {
                [Op.or]: filter.company.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },



    ];

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

            
            if (filter.bank_name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'company_bank_accounts',
                        'bank_name',
                        filter.bank_name,
                    ),
                };
            }
            
            if (filter.iban) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'company_bank_accounts',
                        'iban',
                        filter.iban,
                    ),
                };
            }
            
            if (filter.bic) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'company_bank_accounts',
                        'bic',
                        filter.bic,
                    ),
                };
            }
            
            if (filter.account_holder) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'company_bank_accounts',
                        'account_holder',
                        filter.account_holder,
                    ),
                };
            }
            

            
            

            

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

            
            if (filter.type) {
                where = {
                    ...where,
                type: filter.type,
            };
            }
            
            if (filter.currency) {
                where = {
                    ...where,
                currency: filter.currency,
            };
            }
            
            if (filter.is_default) {
                where = {
                    ...where,
                is_default: filter.is_default,
            };
            }
            
            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.company_bank_accounts.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(
                        'company_bank_accounts',
                        'iban',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

