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

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

        const ar_invoices = await db.ar_invoices.create(
            {
                id: data.id || undefined,
        
        invoiceNumber: data.invoiceNumber
        ||
        null
            ,
            
        invoiceDate: data.invoiceDate
        ||
        null
            ,
            
        dueDate: data.dueDate
        ||
        null
            ,
            
        subtotal: data.subtotal
        ||
        null
            ,
            
        vatAmount: data.vatAmount
        ||
        null
            ,
            
        totalAmountDue: data.totalAmountDue
        ||
        null
            ,
            
        collectedAmount: data.collectedAmount
        ||
        null
            ,
            
        outstandingBalance: data.outstandingBalance
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await ar_invoices.setCustomer( data.customer || null, {
            transaction,
        });
        

        

        

        return ar_invoices;
    }
    

    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 ar_invoicesData = data.map((item, index) => ({
                id: item.id || undefined,
                
                invoiceNumber: item.invoiceNumber
            ||
            null
            ,
            
                invoiceDate: item.invoiceDate
            ||
            null
            ,
            
                dueDate: item.dueDate
            ||
            null
            ,
            
                subtotal: item.subtotal
            ||
            null
            ,
            
                vatAmount: item.vatAmount
            ||
            null
            ,
            
                totalAmountDue: item.totalAmountDue
            ||
            null
            ,
            
                collectedAmount: item.collectedAmount
            ||
            null
            ,
            
                outstandingBalance: item.outstandingBalance
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return ar_invoices;
    }

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

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


        

        const updatePayload = {};
        
        if (data.invoiceNumber !== undefined) updatePayload.invoiceNumber = data.invoiceNumber;
        
        
        if (data.invoiceDate !== undefined) updatePayload.invoiceDate = data.invoiceDate;
        
        
        if (data.dueDate !== undefined) updatePayload.dueDate = data.dueDate;
        
        
        if (data.subtotal !== undefined) updatePayload.subtotal = data.subtotal;
        
        
        if (data.vatAmount !== undefined) updatePayload.vatAmount = data.vatAmount;
        
        
        if (data.totalAmountDue !== undefined) updatePayload.totalAmountDue = data.totalAmountDue;
        
        
        if (data.collectedAmount !== undefined) updatePayload.collectedAmount = data.collectedAmount;
        
        
        if (data.outstandingBalance !== undefined) updatePayload.outstandingBalance = data.outstandingBalance;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.customer !== undefined) {
            await ar_invoices.setCustomer(
              
              data.customer,
              
              { transaction }
            );
        }
        

        
        

        

        return ar_invoices;
    }

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

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

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


        return ar_invoices;
    }

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

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

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

        await ar_invoices.destroy({
            transaction
        });

        return ar_invoices;
    }

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

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

        if (!ar_invoices) {
            return ar_invoices;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.ar_invoice_items_invoice = await ar_invoices.getAr_invoice_items_invoice({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        output.customer = await ar_invoices.getCustomer({
            transaction
        });
        
        

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

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



    ];

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

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

            
            

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

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

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

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

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

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

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

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

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

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

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

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

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

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    outstandingBalance: {
                    ...where.outstandingBalance,
                            [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.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.ar_invoices.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(
                        'ar_invoices',
                        'invoiceNumber',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

