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

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

        const ap_payment_lines = await db.ap_payment_lines.create(
            {
                id: data.id || undefined,
        
        amountPaid: data.amountPaid
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await ap_payment_lines.setPayment( data.payment || null, {
            transaction,
        });
        
        await ap_payment_lines.setInvoice( data.invoice || null, {
            transaction,
        });
        

        

        

        return ap_payment_lines;
    }
    

    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_payment_linesData = data.map((item, index) => ({
                id: item.id || undefined,
                
                amountPaid: item.amountPaid
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return ap_payment_lines;
    }

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

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


        

        const updatePayload = {};
        
        if (data.amountPaid !== undefined) updatePayload.amountPaid = data.amountPaid;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.payment !== undefined) {
            await ap_payment_lines.setPayment(
              
              data.payment,
              
              { transaction }
            );
        }
        
        if (data.invoice !== undefined) {
            await ap_payment_lines.setInvoice(
              
              data.invoice,
              
              { transaction }
            );
        }
        

        
        

        

        return ap_payment_lines;
    }

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

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

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


        return ap_payment_lines;
    }

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

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

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

        await ap_payment_lines.destroy({
            transaction
        });

        return ap_payment_lines;
    }

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

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

        if (!ap_payment_lines) {
            return ap_payment_lines;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.payment = await ap_payment_lines.getPayment({
            transaction
        });
        
        
        output.invoice = await ap_payment_lines.getInvoice({
            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.ap_payments,
        as: 'payment',
        
        where: filter.payment ? {
          [Op.or]: [
            { id: { [Op.in]: filter.payment.split('|').map(term => Utils.uuid(term)) } },
            {
              bankName: {
                [Op.or]: filter.payment.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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



    ];

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

            

            
            

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

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

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

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

            


      

      



            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_payment_lines.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_payment_lines',
                        'amountPaid',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

