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

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

        const payment_allocations = await db.payment_allocations.create(
            {
                id: data.id || undefined,
        
        allocation_date: data.allocation_date
        ||
        null
            ,
            
        amount_allocated: data.amount_allocated
        ||
        null
            ,
            
        notes: data.notes
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

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

        

        

        return payment_allocations;
    }
    

    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 payment_allocationsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                allocation_date: item.allocation_date
            ||
            null
            ,
            
                amount_allocated: item.amount_allocated
            ||
            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 payment_allocations = await db.payment_allocations.bulkCreate(payment_allocationsData, { transaction });

        // For each item created, replace relation files
        

        return payment_allocations;
    }

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


        

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

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

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

        
        

        

        return payment_allocations;
    }

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

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

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


        return payment_allocations;
    }

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

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

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

        await payment_allocations.destroy({
            transaction
        });

        return payment_allocations;
    }

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

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

        if (!payment_allocations) {
            return payment_allocations;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.payment = await payment_allocations.getPayment({
            transaction
        });
        
        
        output.invoice = await payment_allocations.getInvoice({
            transaction
        });
        
        
        output.companies = await payment_allocations.getCompanies({
            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 userCompanies = (user && user.companies?.id) || null;
        

        
        if (userCompanies) {
            if (options?.currentUser?.companiesId) {
                where.companiesId = options.currentUser.companiesId;
            }
        }
        

        offset = currentPage * limit;

        const orderBy = null;

    const transaction = (options && options.transaction) || undefined;

    let include = [

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

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

      {
        model: db.companies,
        as: 'companies',
        
      },



    ];

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

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

            
            

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

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

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

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

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

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

            


      

      

      
      if (filter.companies) {
        const listItems = filter.companies.split('|').map(item => {
          return  Utils.uuid(item)
        });

        where = {
          ...where,
          companiesId: {[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.companiesId;
        }
        

        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.payment_allocations.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(
                        'payment_allocations',
                        'notes',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

