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

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

        const ir_dividends = await db.ir_dividends.create(
            {
                id: data.id || undefined,
        
        declaration_at: data.declaration_at
        ||
        null
            ,
            
        ex_dividend_at: data.ex_dividend_at
        ||
        null
            ,
            
        record_at: data.record_at
        ||
        null
            ,
            
        payable_at: data.payable_at
        ||
        null
            ,
            
        amount: data.amount
        ||
        null
            ,
            
        currency: data.currency
        ||
        null
            ,
            
        frequency: data.frequency
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await ir_dividends.setIr_company( data.ir_company || null, {
            transaction,
        });
        

        

        

        return ir_dividends;
    }
    

    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 ir_dividendsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                declaration_at: item.declaration_at
            ||
            null
            ,
            
                ex_dividend_at: item.ex_dividend_at
            ||
            null
            ,
            
                record_at: item.record_at
            ||
            null
            ,
            
                payable_at: item.payable_at
            ||
            null
            ,
            
                amount: item.amount
            ||
            null
            ,
            
                currency: item.currency
            ||
            null
            ,
            
                frequency: item.frequency
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return ir_dividends;
    }

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

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


        

        const updatePayload = {};
        
        if (data.declaration_at !== undefined) updatePayload.declaration_at = data.declaration_at;
        
        
        if (data.ex_dividend_at !== undefined) updatePayload.ex_dividend_at = data.ex_dividend_at;
        
        
        if (data.record_at !== undefined) updatePayload.record_at = data.record_at;
        
        
        if (data.payable_at !== undefined) updatePayload.payable_at = data.payable_at;
        
        
        if (data.amount !== undefined) updatePayload.amount = data.amount;
        
        
        if (data.currency !== undefined) updatePayload.currency = data.currency;
        
        
        if (data.frequency !== undefined) updatePayload.frequency = data.frequency;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.ir_company !== undefined) {
            await ir_dividends.setIr_company(
              
              data.ir_company,
              
              { transaction }
            );
        }
        

        
        

        

        return ir_dividends;
    }

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

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

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


        return ir_dividends;
    }

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

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

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

        await ir_dividends.destroy({
            transaction
        });

        return ir_dividends;
    }

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

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

        if (!ir_dividends) {
            return ir_dividends;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.ir_company = await ir_dividends.getIr_company({
            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.ir_companies,
        as: 'ir_company',
        
        where: filter.ir_company ? {
          [Op.or]: [
            { id: { [Op.in]: filter.ir_company.split('|').map(term => Utils.uuid(term)) } },
            {
              name: {
                [Op.or]: filter.ir_company.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },



    ];

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

            

            
            
            if (filter.calendarStart && filter.calendarEnd) {
                where = {
                    ...where,
                    [Op.or]: [
                        {
                            ex_dividend_at: {
                                [Op.between]: [filter.calendarStart, filter.calendarEnd],
                            },
                    },
                {
                    payable_at: {
                        [Op.between]: [filter.calendarStart, filter.calendarEnd],
                    },
                },
                ],
            };
            }
            

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

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

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

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

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

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

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

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    payable_at: {
                    ...where.payable_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.currency) {
                where = {
                    ...where,
                currency: filter.currency,
            };
            }
            
            if (filter.frequency) {
                where = {
                    ...where,
                frequency: filter.frequency,
            };
            }
            


      



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

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

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

    
};

