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

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

        const withholding_tax_tables = await db.withholding_tax_tables.create(
            {
                id: data.id || undefined,
        
        periodType: data.periodType
        ||
        null
            ,
            
        salaryFrom: data.salaryFrom
        ||
        null
            ,
            
        salaryTo: data.salaryTo
        ||
        null
            ,
            
        baseTax: data.baseTax
        ||
        null
            ,
            
        excessRate: data.excessRate
        ||
        null
            ,
            
        excessOver: data.excessOver
        ||
        null
            ,
            
        effectiveYear: data.effectiveYear
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        

        

        

        return withholding_tax_tables;
    }
    

    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 withholding_tax_tablesData = data.map((item, index) => ({
                id: item.id || undefined,
                
                periodType: item.periodType
            ||
            null
            ,
            
                salaryFrom: item.salaryFrom
            ||
            null
            ,
            
                salaryTo: item.salaryTo
            ||
            null
            ,
            
                baseTax: item.baseTax
            ||
            null
            ,
            
                excessRate: item.excessRate
            ||
            null
            ,
            
                excessOver: item.excessOver
            ||
            null
            ,
            
                effectiveYear: item.effectiveYear
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return withholding_tax_tables;
    }

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

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


        

        const updatePayload = {};
        
        if (data.periodType !== undefined) updatePayload.periodType = data.periodType;
        
        
        if (data.salaryFrom !== undefined) updatePayload.salaryFrom = data.salaryFrom;
        
        
        if (data.salaryTo !== undefined) updatePayload.salaryTo = data.salaryTo;
        
        
        if (data.baseTax !== undefined) updatePayload.baseTax = data.baseTax;
        
        
        if (data.excessRate !== undefined) updatePayload.excessRate = data.excessRate;
        
        
        if (data.excessOver !== undefined) updatePayload.excessOver = data.excessOver;
        
        
        if (data.effectiveYear !== undefined) updatePayload.effectiveYear = data.effectiveYear;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        

        
        

        

        return withholding_tax_tables;
    }

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

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

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


        return withholding_tax_tables;
    }

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

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

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

        await withholding_tax_tables.destroy({
            transaction
        });

        return withholding_tax_tables;
    }

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

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

        if (!withholding_tax_tables) {
            return withholding_tax_tables;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        

        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 = [



    ];

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

            

            
            

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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




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

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

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

    
};

