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

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

        const monthly_capital_gains = await db.monthly_capital_gains.create(
            {
                id: data.id || undefined,
        
        year: data.year
        ||
        null
            ,
            
        month: data.month
        ||
        null
            ,
            
        asset_type: data.asset_type
        ||
        null
            ,
            
        gross_gain: data.gross_gain
        ||
        null
            ,
            
        gross_loss: data.gross_loss
        ||
        null
            ,
            
        carryforward_loss: data.carryforward_loss
        ||
        null
            ,
            
        net_gain: data.net_gain
        ||
        null
            ,
            
        tax_rate: data.tax_rate
        ||
        null
            ,
            
        tax_due: data.tax_due
        ||
        null
            ,
            
        darf_paid: data.darf_paid
        ||
        false
        
            ,
            
        darf_code: data.darf_code
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await monthly_capital_gains.setDeclaration( data.declaration || null, {
            transaction,
        });
        
        await monthly_capital_gains.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

        

        return monthly_capital_gains;
    }
    

    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 monthly_capital_gainsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                year: item.year
            ||
            null
            ,
            
                month: item.month
            ||
            null
            ,
            
                asset_type: item.asset_type
            ||
            null
            ,
            
                gross_gain: item.gross_gain
            ||
            null
            ,
            
                gross_loss: item.gross_loss
            ||
            null
            ,
            
                carryforward_loss: item.carryforward_loss
            ||
            null
            ,
            
                net_gain: item.net_gain
            ||
            null
            ,
            
                tax_rate: item.tax_rate
            ||
            null
            ,
            
                tax_due: item.tax_due
            ||
            null
            ,
            
                darf_paid: item.darf_paid
            ||
            false
        
            ,
            
                darf_code: item.darf_code
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return monthly_capital_gains;
    }

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

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


        

        const updatePayload = {};
        
        if (data.year !== undefined) updatePayload.year = data.year;
        
        
        if (data.month !== undefined) updatePayload.month = data.month;
        
        
        if (data.asset_type !== undefined) updatePayload.asset_type = data.asset_type;
        
        
        if (data.gross_gain !== undefined) updatePayload.gross_gain = data.gross_gain;
        
        
        if (data.gross_loss !== undefined) updatePayload.gross_loss = data.gross_loss;
        
        
        if (data.carryforward_loss !== undefined) updatePayload.carryforward_loss = data.carryforward_loss;
        
        
        if (data.net_gain !== undefined) updatePayload.net_gain = data.net_gain;
        
        
        if (data.tax_rate !== undefined) updatePayload.tax_rate = data.tax_rate;
        
        
        if (data.tax_due !== undefined) updatePayload.tax_due = data.tax_due;
        
        
        if (data.darf_paid !== undefined) updatePayload.darf_paid = data.darf_paid;
        
        
        if (data.darf_code !== undefined) updatePayload.darf_code = data.darf_code;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.declaration !== undefined) {
            await monthly_capital_gains.setDeclaration(
              
              data.declaration,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await monthly_capital_gains.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        

        

        return monthly_capital_gains;
    }

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

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

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


        return monthly_capital_gains;
    }

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

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

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

        await monthly_capital_gains.destroy({
            transaction
        });

        return monthly_capital_gains;
    }

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

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

        if (!monthly_capital_gains) {
            return monthly_capital_gains;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.declaration = await monthly_capital_gains.getDeclaration({
            transaction
        });
        
        
        output.organizations = await monthly_capital_gains.getOrganizations({
            transaction
        });
        
        

        return output;
    }

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

        
        const user = (options && options.currentUser) || null;
        const userOrganizations = (user && user.organizations?.id) || null;
        

        
        if (userOrganizations) {
            if (options?.currentUser?.organizationsId) {
                where.organizationsId = options.currentUser.organizationsId;
            }
        }
        

        offset = currentPage * limit;

        const orderBy = null;

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

    let include = [

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

      {
        model: db.organizations,
        as: 'organizations',
        
      },



    ];

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

            
            if (filter.darf_code) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'monthly_capital_gains',
                        'darf_code',
                        filter.darf_code,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            
            if (filter.asset_type) {
                where = {
                    ...where,
                asset_type: filter.asset_type,
            };
            }
            
            if (filter.darf_paid) {
                where = {
                    ...where,
                darf_paid: filter.darf_paid,
            };
            }
            


      

      
      if (filter.organizations) {
        const listItems = filter.organizations.split('|').map(item => {
          return  Utils.uuid(item)
        });

        where = {
          ...where,
          organizationsId: {[Op.or]: listItems}
        };
      }
      



            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,
                        },
                    };
                }
            }
        }
        

        
        if (globalAccess) {
            delete where.organizationsId;
        }
        

        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.monthly_capital_gains.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,  globalAccess, organizationId,) {
        let where = {};
        
        
        if (!globalAccess && organizationId) {
            where.organizationId = organizationId;
        }
        

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

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

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

    
};

