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

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

        const cash_movements = await db.cash_movements.create(
            {
                id: data.id || undefined,
        
        movement_at: data.movement_at
        ||
        null
            ,
            
        direction: data.direction
        ||
        null
            ,
            
        amount: data.amount
        ||
        null
            ,
            
        method: data.method
        ||
        null
            ,
            
        source_type: data.source_type
        ||
        null
            ,
            
        reference: data.reference
        ||
        null
            ,
            
        notes: data.notes
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await cash_movements.setPayment( data.payment || null, {
            transaction,
        });
        
        await cash_movements.setExpense( data.expense || null, {
            transaction,
        });
        
        await cash_movements.setRecorded_by_user( data.recorded_by_user || null, {
            transaction,
        });
        

        

        

        return cash_movements;
    }
    

    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 cash_movementsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                movement_at: item.movement_at
            ||
            null
            ,
            
                direction: item.direction
            ||
            null
            ,
            
                amount: item.amount
            ||
            null
            ,
            
                method: item.method
            ||
            null
            ,
            
                source_type: item.source_type
            ||
            null
            ,
            
                reference: item.reference
            ||
            null
            ,
            
                notes: item.notes
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

        // Bulk create items
        const cash_movements = await db.cash_movements.bulkCreate(cash_movementsData, { transaction });

        // For each item created, replace relation files
        

        return cash_movements;
    }

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

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


        

        const updatePayload = {};
        
        if (data.movement_at !== undefined) updatePayload.movement_at = data.movement_at;
        
        
        if (data.direction !== undefined) updatePayload.direction = data.direction;
        
        
        if (data.amount !== undefined) updatePayload.amount = data.amount;
        
        
        if (data.method !== undefined) updatePayload.method = data.method;
        
        
        if (data.source_type !== undefined) updatePayload.source_type = data.source_type;
        
        
        if (data.reference !== undefined) updatePayload.reference = data.reference;
        
        
        if (data.notes !== undefined) updatePayload.notes = data.notes;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.payment !== undefined) {
            await cash_movements.setPayment(
              
              data.payment,
              
              { transaction }
            );
        }
        
        if (data.expense !== undefined) {
            await cash_movements.setExpense(
              
              data.expense,
              
              { transaction }
            );
        }
        
        if (data.recorded_by_user !== undefined) {
            await cash_movements.setRecorded_by_user(
              
              data.recorded_by_user,
              
              { transaction }
            );
        }
        

        
        

        

        return cash_movements;
    }

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

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

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


        return cash_movements;
    }

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

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

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

        await cash_movements.destroy({
            transaction
        });

        return cash_movements;
    }

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

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

        if (!cash_movements) {
            return cash_movements;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.payment = await cash_movements.getPayment({
            transaction
        });
        
        
        output.expense = await cash_movements.getExpense({
            transaction
        });
        
        
        output.recorded_by_user = await cash_movements.getRecorded_by_user({
            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.payments,
        as: 'payment',
        
        where: filter.payment ? {
          [Op.or]: [
            { id: { [Op.in]: filter.payment.split('|').map(term => Utils.uuid(term)) } },
            {
              reference: {
                [Op.or]: filter.payment.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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

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



    ];

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

            
            if (filter.reference) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'cash_movements',
                        'reference',
                        filter.reference,
                    ),
                };
            }
            
            if (filter.notes) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'cash_movements',
                        'notes',
                        filter.notes,
                    ),
                };
            }
            

            
            

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

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    movement_at: {
                    ...where.movement_at,
                            [Op.lte]: end,
                    },
                };
                }
            }
            
            if (filter.amountRange) {
                const [start, end] = filter.amountRange;

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

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

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

            
            if (filter.direction) {
                where = {
                    ...where,
                direction: filter.direction,
            };
            }
            
            if (filter.method) {
                where = {
                    ...where,
                method: filter.method,
            };
            }
            
            if (filter.source_type) {
                where = {
                    ...where,
                source_type: filter.source_type,
            };
            }
            


      

      

      



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

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

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

    
};

