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

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

        const tot_declarations = await db.tot_declarations.create(
            {
                id: data.id || undefined,
        
        status: data.status
        ||
        null
            ,
            
        gross_sales_amount: data.gross_sales_amount
        ||
        null
            ,
            
        tot_rate_percent: data.tot_rate_percent
        ||
        null
            ,
            
        tot_payable_amount: data.tot_payable_amount
        ||
        null
            ,
            
        generated_at: data.generated_at
        ||
        null
            ,
            
        reviewed_at: data.reviewed_at
        ||
        null
            ,
            
        notes: data.notes
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await tot_declarations.setMerchant( data.merchant || null, {
            transaction,
        });
        
        await tot_declarations.setTax_period( data.tax_period || null, {
            transaction,
        });
        
        await tot_declarations.setGenerated_by( data.generated_by || null, {
            transaction,
        });
        
        await tot_declarations.setReviewed_by( data.reviewed_by || null, {
            transaction,
        });
        
        await tot_declarations.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

        
        await FileDBApi.replaceRelationFiles(
            {
                belongsTo: db.tot_declarations.getTableName(),
                belongsToColumn: 'pdf_file',
                belongsToId: tot_declarations.id,
            },
            data.pdf_file,
            options,
        );
        
        await FileDBApi.replaceRelationFiles(
            {
                belongsTo: db.tot_declarations.getTableName(),
                belongsToColumn: 'excel_file',
                belongsToId: tot_declarations.id,
            },
            data.excel_file,
            options,
        );
        
        await FileDBApi.replaceRelationFiles(
            {
                belongsTo: db.tot_declarations.getTableName(),
                belongsToColumn: 'revenue_office_export_file',
                belongsToId: tot_declarations.id,
            },
            data.revenue_office_export_file,
            options,
        );
        

        return tot_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 tot_declarationsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                status: item.status
            ||
            null
            ,
            
                gross_sales_amount: item.gross_sales_amount
            ||
            null
            ,
            
                tot_rate_percent: item.tot_rate_percent
            ||
            null
            ,
            
                tot_payable_amount: item.tot_payable_amount
            ||
            null
            ,
            
                generated_at: item.generated_at
            ||
            null
            ,
            
                reviewed_at: item.reviewed_at
            ||
            null
            ,
            
                notes: item.notes
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        
        for (let i = 0; i < tot_declarations.length; i++) {
            await FileDBApi.replaceRelationFiles(
                {
                    belongsTo: db.tot_declarations.getTableName(),
                    belongsToColumn: 'pdf_file',
                    belongsToId: tot_declarations[i].id,
                },
                data[i].pdf_file,
                options,
            );
        }
        
        for (let i = 0; i < tot_declarations.length; i++) {
            await FileDBApi.replaceRelationFiles(
                {
                    belongsTo: db.tot_declarations.getTableName(),
                    belongsToColumn: 'excel_file',
                    belongsToId: tot_declarations[i].id,
                },
                data[i].excel_file,
                options,
            );
        }
        
        for (let i = 0; i < tot_declarations.length; i++) {
            await FileDBApi.replaceRelationFiles(
                {
                    belongsTo: db.tot_declarations.getTableName(),
                    belongsToColumn: 'revenue_office_export_file',
                    belongsToId: tot_declarations[i].id,
                },
                data[i].revenue_office_export_file,
                options,
            );
        }
        

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


        

        const updatePayload = {};
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.gross_sales_amount !== undefined) updatePayload.gross_sales_amount = data.gross_sales_amount;
        
        
        if (data.tot_rate_percent !== undefined) updatePayload.tot_rate_percent = data.tot_rate_percent;
        
        
        if (data.tot_payable_amount !== undefined) updatePayload.tot_payable_amount = data.tot_payable_amount;
        
        
        if (data.generated_at !== undefined) updatePayload.generated_at = data.generated_at;
        
        
        if (data.reviewed_at !== undefined) updatePayload.reviewed_at = data.reviewed_at;
        
        
        if (data.notes !== undefined) updatePayload.notes = data.notes;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.merchant !== undefined) {
            await tot_declarations.setMerchant(
              
              data.merchant,
              
              { transaction }
            );
        }
        
        if (data.tax_period !== undefined) {
            await tot_declarations.setTax_period(
              
              data.tax_period,
              
              { transaction }
            );
        }
        
        if (data.generated_by !== undefined) {
            await tot_declarations.setGenerated_by(
              
              data.generated_by,
              
              { transaction }
            );
        }
        
        if (data.reviewed_by !== undefined) {
            await tot_declarations.setReviewed_by(
              
              data.reviewed_by,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await tot_declarations.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        

        
        await FileDBApi.replaceRelationFiles(
            {
                belongsTo: db.tot_declarations.getTableName(),
                belongsToColumn: 'pdf_file',
                belongsToId: tot_declarations.id,
            },
            data.pdf_file,
            options,
        );
        
        await FileDBApi.replaceRelationFiles(
            {
                belongsTo: db.tot_declarations.getTableName(),
                belongsToColumn: 'excel_file',
                belongsToId: tot_declarations.id,
            },
            data.excel_file,
            options,
        );
        
        await FileDBApi.replaceRelationFiles(
            {
                belongsTo: db.tot_declarations.getTableName(),
                belongsToColumn: 'revenue_office_export_file',
                belongsToId: tot_declarations.id,
            },
            data.revenue_office_export_file,
            options,
        );
        

        return tot_declarations;
    }

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

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

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


        return tot_declarations;
    }

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

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

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

        await tot_declarations.destroy({
            transaction
        });

        return tot_declarations;
    }

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

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

        if (!tot_declarations) {
            return tot_declarations;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.merchant = await tot_declarations.getMerchant({
            transaction
        });
        
        
        output.tax_period = await tot_declarations.getTax_period({
            transaction
        });
        
        
        output.generated_by = await tot_declarations.getGenerated_by({
            transaction
        });
        
        
        output.reviewed_by = await tot_declarations.getReviewed_by({
            transaction
        });
        
        
        output.pdf_file = await tot_declarations.getPdf_file({
            transaction
        });
        
        
        output.excel_file = await tot_declarations.getExcel_file({
            transaction
        });
        
        
        output.revenue_office_export_file = await tot_declarations.getRevenue_office_export_file({
            transaction
        });
        
        
        output.organizations = await tot_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.merchants,
        as: 'merchant',
        
        where: filter.merchant ? {
          [Op.or]: [
            { id: { [Op.in]: filter.merchant.split('|').map(term => Utils.uuid(term)) } },
            {
              business_name: {
                [Op.or]: filter.merchant.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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

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

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

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



      {
        model: db.file,
        as: 'pdf_file',
      },

      {
        model: db.file,
        as: 'excel_file',
      },

      {
        model: db.file,
        as: 'revenue_office_export_file',
      },

    ];

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

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

            
            

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

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

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

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

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

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

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

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

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

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    reviewed_at: {
                    ...where.reviewed_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.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.tot_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(
                        'tot_declarations',
                        'status',
                        query,
                    ),
                ],
            };
        }

        const records = await db.tot_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,
        }));
    }

    
};

