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

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

        const income_payers_pj = await db.income_payers_pj.create(
            {
                id: data.id || undefined,
        
        payer_cnpj: data.payer_cnpj
        ||
        null
            ,
            
        payer_name: data.payer_name
        ||
        null
            ,
            
        taxable_income: data.taxable_income
        ||
        null
            ,
            
        official_deductions: data.official_deductions
        ||
        null
            ,
            
        inss_withheld: data.inss_withheld
        ||
        null
            ,
            
        tax_withheld: data.tax_withheld
        ||
        null
            ,
            
        thirteenth_salary: data.thirteenth_salary
        ||
        null
            ,
            
        informe_document_url: data.informe_document_url
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

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

        

        

        return income_payers_pj;
    }
    

    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_payers_pjData = data.map((item, index) => ({
                id: item.id || undefined,
                
                payer_cnpj: item.payer_cnpj
            ||
            null
            ,
            
                payer_name: item.payer_name
            ||
            null
            ,
            
                taxable_income: item.taxable_income
            ||
            null
            ,
            
                official_deductions: item.official_deductions
            ||
            null
            ,
            
                inss_withheld: item.inss_withheld
            ||
            null
            ,
            
                tax_withheld: item.tax_withheld
            ||
            null
            ,
            
                thirteenth_salary: item.thirteenth_salary
            ||
            null
            ,
            
                informe_document_url: item.informe_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_payers_pj = await db.income_payers_pj.bulkCreate(income_payers_pjData, { transaction });

        // For each item created, replace relation files
        

        return income_payers_pj;
    }

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


        

        const updatePayload = {};
        
        if (data.payer_cnpj !== undefined) updatePayload.payer_cnpj = data.payer_cnpj;
        
        
        if (data.payer_name !== undefined) updatePayload.payer_name = data.payer_name;
        
        
        if (data.taxable_income !== undefined) updatePayload.taxable_income = data.taxable_income;
        
        
        if (data.official_deductions !== undefined) updatePayload.official_deductions = data.official_deductions;
        
        
        if (data.inss_withheld !== undefined) updatePayload.inss_withheld = data.inss_withheld;
        
        
        if (data.tax_withheld !== undefined) updatePayload.tax_withheld = data.tax_withheld;
        
        
        if (data.thirteenth_salary !== undefined) updatePayload.thirteenth_salary = data.thirteenth_salary;
        
        
        if (data.informe_document_url !== undefined) updatePayload.informe_document_url = data.informe_document_url;
        
        
        updatePayload.updatedById = currentUser.id;

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

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

        
        

        

        return income_payers_pj;
    }

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

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

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


        return income_payers_pj;
    }

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

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

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

        await income_payers_pj.destroy({
            transaction
        });

        return income_payers_pj;
    }

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

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

        if (!income_payers_pj) {
            return income_payers_pj;
        }

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

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

            
            

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

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

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

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

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

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

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

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

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

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

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

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

            


      

      
      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_payers_pj.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_payers_pj',
                        'payer_name',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

