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

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

        const ap_invoices = await db.ap_invoices.create(
            {
                id: data.id || undefined,
        
        invoiceNumber: data.invoiceNumber
        ||
        null
            ,
            
        vendorInvoiceNumber: data.vendorInvoiceNumber
        ||
        null
            ,
            
        invoiceDate: data.invoiceDate
        ||
        null
            ,
            
        receiptDate: data.receiptDate
        ||
        null
            ,
            
        dueDate: data.dueDate
        ||
        null
            ,
            
        grossAmount: data.grossAmount
        ||
        null
            ,
            
        vatAmount: data.vatAmount
        ||
        null
            ,
            
        ewtAmount: data.ewtAmount
        ||
        null
            ,
            
        netPayable: data.netPayable
        ||
        null
            ,
            
        description: data.description
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await ap_invoices.setVendor( data.vendor || null, {
            transaction,
        });
        
        await ap_invoices.setGlAccount( data.glAccount || null, {
            transaction,
        });
        
        await ap_invoices.setCostCenter( data.costCenter || null, {
            transaction,
        });
        
        await ap_invoices.setJournalEntry( data.journalEntry || null, {
            transaction,
        });
        

        

        

        return ap_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 ap_invoicesData = data.map((item, index) => ({
                id: item.id || undefined,
                
                invoiceNumber: item.invoiceNumber
            ||
            null
            ,
            
                vendorInvoiceNumber: item.vendorInvoiceNumber
            ||
            null
            ,
            
                invoiceDate: item.invoiceDate
            ||
            null
            ,
            
                receiptDate: item.receiptDate
            ||
            null
            ,
            
                dueDate: item.dueDate
            ||
            null
            ,
            
                grossAmount: item.grossAmount
            ||
            null
            ,
            
                vatAmount: item.vatAmount
            ||
            null
            ,
            
                ewtAmount: item.ewtAmount
            ||
            null
            ,
            
                netPayable: item.netPayable
            ||
            null
            ,
            
                description: item.description
            ||
            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 ap_invoices = await db.ap_invoices.bulkCreate(ap_invoicesData, { transaction });

        // For each item created, replace relation files
        

        return ap_invoices;
    }

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

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


        

        const updatePayload = {};
        
        if (data.invoiceNumber !== undefined) updatePayload.invoiceNumber = data.invoiceNumber;
        
        
        if (data.vendorInvoiceNumber !== undefined) updatePayload.vendorInvoiceNumber = data.vendorInvoiceNumber;
        
        
        if (data.invoiceDate !== undefined) updatePayload.invoiceDate = data.invoiceDate;
        
        
        if (data.receiptDate !== undefined) updatePayload.receiptDate = data.receiptDate;
        
        
        if (data.dueDate !== undefined) updatePayload.dueDate = data.dueDate;
        
        
        if (data.grossAmount !== undefined) updatePayload.grossAmount = data.grossAmount;
        
        
        if (data.vatAmount !== undefined) updatePayload.vatAmount = data.vatAmount;
        
        
        if (data.ewtAmount !== undefined) updatePayload.ewtAmount = data.ewtAmount;
        
        
        if (data.netPayable !== undefined) updatePayload.netPayable = data.netPayable;
        
        
        if (data.description !== undefined) updatePayload.description = data.description;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.vendor !== undefined) {
            await ap_invoices.setVendor(
              
              data.vendor,
              
              { transaction }
            );
        }
        
        if (data.glAccount !== undefined) {
            await ap_invoices.setGlAccount(
              
              data.glAccount,
              
              { transaction }
            );
        }
        
        if (data.costCenter !== undefined) {
            await ap_invoices.setCostCenter(
              
              data.costCenter,
              
              { transaction }
            );
        }
        
        if (data.journalEntry !== undefined) {
            await ap_invoices.setJournalEntry(
              
              data.journalEntry,
              
              { transaction }
            );
        }
        

        
        

        

        return ap_invoices;
    }

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

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

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


        return ap_invoices;
    }

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

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

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

        await ap_invoices.destroy({
            transaction
        });

        return ap_invoices;
    }

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

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

        if (!ap_invoices) {
            return ap_invoices;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.ap_payment_lines_invoice = await ap_invoices.getAp_payment_lines_invoice({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.vendor = await ap_invoices.getVendor({
            transaction
        });
        
        
        output.glAccount = await ap_invoices.getGlAccount({
            transaction
        });
        
        
        output.costCenter = await ap_invoices.getCostCenter({
            transaction
        });
        
        
        output.journalEntry = await ap_invoices.getJournalEntry({
            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.vendors,
        as: 'vendor',
        
        where: filter.vendor ? {
          [Op.or]: [
            { id: { [Op.in]: filter.vendor.split('|').map(term => Utils.uuid(term)) } },
            {
              vendorName: {
                [Op.or]: filter.vendor.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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

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

      {
        model: db.journal_entries,
        as: 'journalEntry',
        
        where: filter.journalEntry ? {
          [Op.or]: [
            { id: { [Op.in]: filter.journalEntry.split('|').map(term => Utils.uuid(term)) } },
            {
              entryNumber: {
                [Op.or]: filter.journalEntry.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(
                        'ap_invoices',
                        'invoiceNumber',
                        filter.invoiceNumber,
                    ),
                };
            }
            
            if (filter.vendorInvoiceNumber) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'ap_invoices',
                        'vendorInvoiceNumber',
                        filter.vendorInvoiceNumber,
                    ),
                };
            }
            
            if (filter.description) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'ap_invoices',
                        'description',
                        filter.description,
                    ),
                };
            }
            

            
            

            
            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.receiptDateRange) {
                const [start, end] = filter.receiptDateRange;

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

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

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

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

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

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

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

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

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

    
};

