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

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

        const declarations = await db.declarations.create(
            {
                id: data.id || undefined,
        
        base_year: data.base_year
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        tax_model: data.tax_model
        ||
        null
            ,
            
        declaration_type: data.declaration_type
        ||
        null
            ,
            
        previous_receipt_number: data.previous_receipt_number
        ||
        null
            ,
            
        tax_calculated: data.tax_calculated
        ||
        null
            ,
            
        tax_withheld: data.tax_withheld
        ||
        null
            ,
            
        refund_amount: data.refund_amount
        ||
        null
            ,
            
        payable_amount: data.payable_amount
        ||
        null
            ,
            
        risk_score: data.risk_score
        ||
        null
            ,
            
        risk_details_json: data.risk_details_json
        ||
        null
            ,
            
        dec_file_url: data.dec_file_url
        ||
        null
            ,
            
        submitted_at: data.submitted_at
        ||
        null
            ,
            
        last_calculated_at: data.last_calculated_at
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await declarations.setUser( data.user || null, {
            transaction,
        });
        
        await declarations.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

        

        return declarations;
    }
    

    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 declarationsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                base_year: item.base_year
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
                tax_model: item.tax_model
            ||
            null
            ,
            
                declaration_type: item.declaration_type
            ||
            null
            ,
            
                previous_receipt_number: item.previous_receipt_number
            ||
            null
            ,
            
                tax_calculated: item.tax_calculated
            ||
            null
            ,
            
                tax_withheld: item.tax_withheld
            ||
            null
            ,
            
                refund_amount: item.refund_amount
            ||
            null
            ,
            
                payable_amount: item.payable_amount
            ||
            null
            ,
            
                risk_score: item.risk_score
            ||
            null
            ,
            
                risk_details_json: item.risk_details_json
            ||
            null
            ,
            
                dec_file_url: item.dec_file_url
            ||
            null
            ,
            
                submitted_at: item.submitted_at
            ||
            null
            ,
            
                last_calculated_at: item.last_calculated_at
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return declarations;
    }

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


        

        const updatePayload = {};
        
        if (data.base_year !== undefined) updatePayload.base_year = data.base_year;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.tax_model !== undefined) updatePayload.tax_model = data.tax_model;
        
        
        if (data.declaration_type !== undefined) updatePayload.declaration_type = data.declaration_type;
        
        
        if (data.previous_receipt_number !== undefined) updatePayload.previous_receipt_number = data.previous_receipt_number;
        
        
        if (data.tax_calculated !== undefined) updatePayload.tax_calculated = data.tax_calculated;
        
        
        if (data.tax_withheld !== undefined) updatePayload.tax_withheld = data.tax_withheld;
        
        
        if (data.refund_amount !== undefined) updatePayload.refund_amount = data.refund_amount;
        
        
        if (data.payable_amount !== undefined) updatePayload.payable_amount = data.payable_amount;
        
        
        if (data.risk_score !== undefined) updatePayload.risk_score = data.risk_score;
        
        
        if (data.risk_details_json !== undefined) updatePayload.risk_details_json = data.risk_details_json;
        
        
        if (data.dec_file_url !== undefined) updatePayload.dec_file_url = data.dec_file_url;
        
        
        if (data.submitted_at !== undefined) updatePayload.submitted_at = data.submitted_at;
        
        
        if (data.last_calculated_at !== undefined) updatePayload.last_calculated_at = data.last_calculated_at;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.user !== undefined) {
            await declarations.setUser(
              
              data.user,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await declarations.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        

        

        return declarations;
    }

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

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

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


        return declarations;
    }

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

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

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

        await declarations.destroy({
            transaction
        });

        return declarations;
    }

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

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

        if (!declarations) {
            return declarations;
        }

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

        
        
        
        
        
        
        
        
        output.dependents_declaration = await declarations.getDependents_declaration({
            transaction
        });
        
        
        output.data_sources_declaration = await declarations.getData_sources_declaration({
            transaction
        });
        
        
        output.transactions_declaration = await declarations.getTransactions_declaration({
            transaction
        });
        
        
        output.documents_declaration = await declarations.getDocuments_declaration({
            transaction
        });
        
        
        output.income_payers_pj_declaration = await declarations.getIncome_payers_pj_declaration({
            transaction
        });
        
        
        output.income_carne_leao_monthly_declaration = await declarations.getIncome_carne_leao_monthly_declaration({
            transaction
        });
        
        
        output.exempt_incomes_declaration = await declarations.getExempt_incomes_declaration({
            transaction
        });
        
        
        output.exclusive_incomes_declaration = await declarations.getExclusive_incomes_declaration({
            transaction
        });
        
        
        output.assets_declaration = await declarations.getAssets_declaration({
            transaction
        });
        
        
        output.debts_declaration = await declarations.getDebts_declaration({
            transaction
        });
        
        
        output.deductible_payments_declaration = await declarations.getDeductible_payments_declaration({
            transaction
        });
        
        
        output.investment_positions_declaration = await declarations.getInvestment_positions_declaration({
            transaction
        });
        
        
        output.trades_declaration = await declarations.getTrades_declaration({
            transaction
        });
        
        
        output.monthly_capital_gains_declaration = await declarations.getMonthly_capital_gains_declaration({
            transaction
        });
        
        
        output.risk_analyses_declaration = await declarations.getRisk_analyses_declaration({
            transaction
        });
        
        
        
        
        
        
        
        output.job_runs_declaration = await declarations.getJob_runs_declaration({
            transaction
        });
        
        
        
        output.user = await declarations.getUser({
            transaction
        });
        
        
        output.organizations = await declarations.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.users,
        as: 'user',
        
        where: filter.user ? {
          [Op.or]: [
            { id: { [Op.in]: filter.user.split('|').map(term => Utils.uuid(term)) } },
            {
              firstName: {
                [Op.or]: filter.user.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.previous_receipt_number) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'declarations',
                        'previous_receipt_number',
                        filter.previous_receipt_number,
                    ),
                };
            }
            
            if (filter.risk_details_json) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'declarations',
                        'risk_details_json',
                        filter.risk_details_json,
                    ),
                };
            }
            
            if (filter.dec_file_url) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'declarations',
                        'dec_file_url',
                        filter.dec_file_url,
                    ),
                };
            }
            

            
            

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

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

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

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    tax_calculated: {
                    ...where.tax_calculated,
                            [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.refund_amountRange) {
                const [start, end] = filter.refund_amountRange;

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

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

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

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

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

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

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

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

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

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

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

            
            if (filter.status) {
                where = {
                    ...where,
                status: filter.status,
            };
            }
            
            if (filter.tax_model) {
                where = {
                    ...where,
                tax_model: filter.tax_model,
            };
            }
            
            if (filter.declaration_type) {
                where = {
                    ...where,
                declaration_type: filter.declaration_type,
            };
            }
            


      

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

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

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

    
};

