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

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

        const bank_accounts = await db.bank_accounts.create(
            {
                id: data.id || undefined,
        
        account_title: data.account_title
        ||
        null
            ,
            
        account_number: data.account_number
        ||
        null
            ,
            
        iban: data.iban
        ||
        null
            ,
            
        card_number: data.card_number
        ||
        null
            ,
            
        opening_balance: data.opening_balance
        ||
        null
            ,
            
        is_active: data.is_active
        ||
        false
        
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await bank_accounts.setBusiness( data.business || null, {
            transaction,
        });
        
        await bank_accounts.setBank( data.bank || null, {
            transaction,
        });
        
        await bank_accounts.setBranch( data.branch || null, {
            transaction,
        });
        
        await bank_accounts.setCurrency( data.currency || null, {
            transaction,
        });
        

        

        

        return 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 bank_accountsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                account_title: item.account_title
            ||
            null
            ,
            
                account_number: item.account_number
            ||
            null
            ,
            
                iban: item.iban
            ||
            null
            ,
            
                card_number: item.card_number
            ||
            null
            ,
            
                opening_balance: item.opening_balance
            ||
            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 bank_accounts = await db.bank_accounts.bulkCreate(bank_accountsData, { transaction });

        // For each item created, replace relation files
        

        return bank_accounts;
    }

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

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


        

        const updatePayload = {};
        
        if (data.account_title !== undefined) updatePayload.account_title = data.account_title;
        
        
        if (data.account_number !== undefined) updatePayload.account_number = data.account_number;
        
        
        if (data.iban !== undefined) updatePayload.iban = data.iban;
        
        
        if (data.card_number !== undefined) updatePayload.card_number = data.card_number;
        
        
        if (data.opening_balance !== undefined) updatePayload.opening_balance = data.opening_balance;
        
        
        if (data.is_active !== undefined) updatePayload.is_active = data.is_active;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.business !== undefined) {
            await bank_accounts.setBusiness(
              
              data.business,
              
              { transaction }
            );
        }
        
        if (data.bank !== undefined) {
            await bank_accounts.setBank(
              
              data.bank,
              
              { transaction }
            );
        }
        
        if (data.branch !== undefined) {
            await bank_accounts.setBranch(
              
              data.branch,
              
              { transaction }
            );
        }
        
        if (data.currency !== undefined) {
            await bank_accounts.setCurrency(
              
              data.currency,
              
              { transaction }
            );
        }
        

        
        

        

        return bank_accounts;
    }

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

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

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


        return bank_accounts;
    }

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

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

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

        await bank_accounts.destroy({
            transaction
        });

        return bank_accounts;
    }

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

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

        if (!bank_accounts) {
            return bank_accounts;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.pos_terminals_bank_account = await bank_accounts.getPos_terminals_bank_account({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.business = await bank_accounts.getBusiness({
            transaction
        });
        
        
        output.bank = await bank_accounts.getBank({
            transaction
        });
        
        
        output.branch = await bank_accounts.getBranch({
            transaction
        });
        
        
        output.currency = await bank_accounts.getCurrency({
            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.businesses,
        as: 'business',
        
        where: filter.business ? {
          [Op.or]: [
            { id: { [Op.in]: filter.business.split('|').map(term => Utils.uuid(term)) } },
            {
              trade_name: {
                [Op.or]: filter.business.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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

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

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



    ];

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

            
            if (filter.account_title) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'bank_accounts',
                        'account_title',
                        filter.account_title,
                    ),
                };
            }
            
            if (filter.account_number) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'bank_accounts',
                        'account_number',
                        filter.account_number,
                    ),
                };
            }
            
            if (filter.iban) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'bank_accounts',
                        'iban',
                        filter.iban,
                    ),
                };
            }
            
            if (filter.card_number) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'bank_accounts',
                        'card_number',
                        filter.card_number,
                    ),
                };
            }
            

            
            

            
            if (filter.opening_balanceRange) {
                const [start, end] = filter.opening_balanceRange;

                if (start !== undefined && start !== null && start !== '') {
                    where = {
                        ...where,
                    opening_balance: {
                    ...where.opening_balance,
                            [Op.gte]: start,
                    },
                };
                }

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    opening_balance: {
                    ...where.opening_balance,
                            [Op.lte]: end,
                    },
                };
                }
            }
            

            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.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(
                        'bank_accounts',
                        'account_title',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

