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

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

        const income_carne_leao_monthly = await db.income_carne_leao_monthly.create(
            {
                id: data.id || undefined,
        
        year: data.year
        ||
        null
            ,
            
        month: data.month
        ||
        null
            ,
            
        gross_revenue: data.gross_revenue
        ||
        null
            ,
            
        bookkeeping_deductions: data.bookkeeping_deductions
        ||
        null
            ,
            
        taxable_base: data.taxable_base
        ||
        null
            ,
            
        tax_due: data.tax_due
        ||
        null
            ,
            
        darf_paid: data.darf_paid
        ||
        false
        
            ,
            
        darf_document_url: data.darf_document_url
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

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

        

        

        return income_carne_leao_monthly;
    }
    

    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 income_carne_leao_monthlyData = data.map((item, index) => ({
                id: item.id || undefined,
                
                year: item.year
            ||
            null
            ,
            
                month: item.month
            ||
            null
            ,
            
                gross_revenue: item.gross_revenue
            ||
            null
            ,
            
                bookkeeping_deductions: item.bookkeeping_deductions
            ||
            null
            ,
            
                taxable_base: item.taxable_base
            ||
            null
            ,
            
                tax_due: item.tax_due
            ||
            null
            ,
            
                darf_paid: item.darf_paid
            ||
            false
        
            ,
            
                darf_document_url: item.darf_document_url
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return income_carne_leao_monthly;
    }

    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 income_carne_leao_monthly = await db.income_carne_leao_monthly.findByPk(id, {}, {transaction});


        

        const updatePayload = {};
        
        if (data.year !== undefined) updatePayload.year = data.year;
        
        
        if (data.month !== undefined) updatePayload.month = data.month;
        
        
        if (data.gross_revenue !== undefined) updatePayload.gross_revenue = data.gross_revenue;
        
        
        if (data.bookkeeping_deductions !== undefined) updatePayload.bookkeeping_deductions = data.bookkeeping_deductions;
        
        
        if (data.taxable_base !== undefined) updatePayload.taxable_base = data.taxable_base;
        
        
        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_document_url !== undefined) updatePayload.darf_document_url = data.darf_document_url;
        
        
        updatePayload.updatedById = currentUser.id;

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

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

        
        

        

        return income_carne_leao_monthly;
    }

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

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

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


        return income_carne_leao_monthly;
    }

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

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

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

        await income_carne_leao_monthly.destroy({
            transaction
        });

        return income_carne_leao_monthly;
    }

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

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

        if (!income_carne_leao_monthly) {
            return income_carne_leao_monthly;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.declaration = await income_carne_leao_monthly.getDeclaration({
            transaction
        });
        
        
        output.organizations = await income_carne_leao_monthly.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_document_url) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'income_carne_leao_monthly',
                        'darf_document_url',
                        filter.darf_document_url,
                    ),
                };
            }
            

            
            

            
            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_revenueRange) {
                const [start, end] = filter.gross_revenueRange;

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

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

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

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

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    taxable_base: {
                    ...where.taxable_base,
                            [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.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.income_carne_leao_monthly.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(
                        'income_carne_leao_monthly',
                        'year',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

