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

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

        const ap_payments = await db.ap_payments.create(
            {
                id: data.id || undefined,
        
        paymentDate: data.paymentDate
        ||
        null
            ,
            
        paymentMode: data.paymentMode
        ||
        null
            ,
            
        checkNumber: data.checkNumber
        ||
        null
            ,
            
        bankName: data.bankName
        ||
        null
            ,
            
        totalAmount: data.totalAmount
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await ap_payments.setCreatedByUser( data.createdByUser || null, {
            transaction,
        });
        
        await ap_payments.setApprovedByUser( data.approvedByUser || null, {
            transaction,
        });
        

        
        await ap_payments.setLines(data.lines || [], {
            transaction,
        });
        

        

        return ap_payments;
    }
    

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

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

        // For each item created, replace relation files
        

        return ap_payments;
    }

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

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


        

        const updatePayload = {};
        
        if (data.paymentDate !== undefined) updatePayload.paymentDate = data.paymentDate;
        
        
        if (data.paymentMode !== undefined) updatePayload.paymentMode = data.paymentMode;
        
        
        if (data.checkNumber !== undefined) updatePayload.checkNumber = data.checkNumber;
        
        
        if (data.bankName !== undefined) updatePayload.bankName = data.bankName;
        
        
        if (data.totalAmount !== undefined) updatePayload.totalAmount = data.totalAmount;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.createdByUser !== undefined) {
            await ap_payments.setCreatedByUser(
              
              data.createdByUser,
              
              { transaction }
            );
        }
        
        if (data.approvedByUser !== undefined) {
            await ap_payments.setApprovedByUser(
              
              data.approvedByUser,
              
              { transaction }
            );
        }
        

        
        
        if (data.lines !== undefined) {
            await ap_payments.setLines(data.lines, { transaction });
        }
        

        

        return ap_payments;
    }

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

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

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


        return ap_payments;
    }

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

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

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

        await ap_payments.destroy({
            transaction
        });

        return ap_payments;
    }

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

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

        if (!ap_payments) {
            return ap_payments;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.ap_payment_lines_payment = await ap_payments.getAp_payment_lines_payment({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.createdByUser = await ap_payments.getCreatedByUser({
            transaction
        });
        
        
        output.approvedByUser = await ap_payments.getApprovedByUser({
            transaction
        });
        
        
        output.lines = await ap_payments.getLines({
            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.users,
        as: 'createdByUser',
        
        where: filter.createdByUser ? {
          [Op.or]: [
            { id: { [Op.in]: filter.createdByUser.split('|').map(term => Utils.uuid(term)) } },
            {
              firstName: {
                [Op.or]: filter.createdByUser.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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


      {
        model: db.ap_payment_lines,
        as: 'lines',
        required: false,
      },


    ];

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

            
            if (filter.checkNumber) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'ap_payments',
                        'checkNumber',
                        filter.checkNumber,
                    ),
                };
            }
            
            if (filter.bankName) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'ap_payments',
                        'bankName',
                        filter.bankName,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

            
            if (filter.paymentMode) {
                where = {
                    ...where,
                paymentMode: filter.paymentMode,
            };
            }
            


      

      


      if (filter.lines) {
        const searchTerms = filter.lines.split('|');

        include = [
          {
            model: db.ap_payment_lines,
            as: 'lines_filter',
            required: searchTerms.length > 0,
            where: searchTerms.length > 0 ? {
              [Op.or]: [
                { id: { [Op.in]: searchTerms.map(term => Utils.uuid(term)) } },
                { 
                  amountPaid: {
                    [Op.or]: searchTerms.map(term => ({ [Op.iLike]: `%${term}%` }))
                  }
                }
              ]
            } : undefined
          },
          ...include,
        ]
      }


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

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

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

    
};

