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

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

        const vat_declarations = await db.vat_declarations.create(
            {
                id: data.id || undefined,
        
        status: data.status
        ||
        null
            ,
            
        total_sales_amount: data.total_sales_amount
        ||
        null
            ,
            
        taxable_sales_amount: data.taxable_sales_amount
        ||
        null
            ,
            
        output_vat_amount: data.output_vat_amount
        ||
        null
            ,
            
        total_purchases_amount: data.total_purchases_amount
        ||
        null
            ,
            
        input_vat_amount: data.input_vat_amount
        ||
        null
            ,
            
        vat_payable_amount: data.vat_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 vat_declarations.setMerchant( data.merchant || null, {
            transaction,
        });
        
        await vat_declarations.setTax_period( data.tax_period || null, {
            transaction,
        });
        
        await vat_declarations.setGenerated_by( data.generated_by || null, {
            transaction,
        });
        
        await vat_declarations.setReviewed_by( data.reviewed_by || null, {
            transaction,
        });
        
        await vat_declarations.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

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

        return vat_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 vat_declarationsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                status: item.status
            ||
            null
            ,
            
                total_sales_amount: item.total_sales_amount
            ||
            null
            ,
            
                taxable_sales_amount: item.taxable_sales_amount
            ||
            null
            ,
            
                output_vat_amount: item.output_vat_amount
            ||
            null
            ,
            
                total_purchases_amount: item.total_purchases_amount
            ||
            null
            ,
            
                input_vat_amount: item.input_vat_amount
            ||
            null
            ,
            
                vat_payable_amount: item.vat_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 vat_declarations = await db.vat_declarations.bulkCreate(vat_declarationsData, { transaction });

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

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


        

        const updatePayload = {};
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.total_sales_amount !== undefined) updatePayload.total_sales_amount = data.total_sales_amount;
        
        
        if (data.taxable_sales_amount !== undefined) updatePayload.taxable_sales_amount = data.taxable_sales_amount;
        
        
        if (data.output_vat_amount !== undefined) updatePayload.output_vat_amount = data.output_vat_amount;
        
        
        if (data.total_purchases_amount !== undefined) updatePayload.total_purchases_amount = data.total_purchases_amount;
        
        
        if (data.input_vat_amount !== undefined) updatePayload.input_vat_amount = data.input_vat_amount;
        
        
        if (data.vat_payable_amount !== undefined) updatePayload.vat_payable_amount = data.vat_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 vat_declarations.update(updatePayload, {transaction});

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

        
        

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

        return vat_declarations;
    }

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

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

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


        return vat_declarations;
    }

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

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

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

        await vat_declarations.destroy({
            transaction
        });

        return vat_declarations;
    }

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

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

        if (!vat_declarations) {
            return vat_declarations;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.merchant = await vat_declarations.getMerchant({
            transaction
        });
        
        
        output.tax_period = await vat_declarations.getTax_period({
            transaction
        });
        
        
        output.generated_by = await vat_declarations.getGenerated_by({
            transaction
        });
        
        
        output.reviewed_by = await vat_declarations.getReviewed_by({
            transaction
        });
        
        
        output.pdf_file = await vat_declarations.getPdf_file({
            transaction
        });
        
        
        output.excel_file = await vat_declarations.getExcel_file({
            transaction
        });
        
        
        output.revenue_office_export_file = await vat_declarations.getRevenue_office_export_file({
            transaction
        });
        
        
        output.organizations = await vat_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(
                        'vat_declarations',
                        'notes',
                        filter.notes,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
};

