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

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

        const payments = await db.payments.create(
            {
                id: data.id || undefined,
        
        payment_number: data.payment_number
        ||
        null
            ,
            
        direction: data.direction
        ||
        null
            ,
            
        counterparty_type: data.counterparty_type
        ||
        null
            ,
            
        paid_at: data.paid_at
        ||
        null
            ,
            
        amount: data.amount
        ||
        null
            ,
            
        currency: data.currency
        ||
        null
            ,
            
        method: data.method
        ||
        null
            ,
            
        reference: data.reference
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await payments.setTenant( data.tenant || null, {
            transaction,
        });
        
        await payments.setCustomer( data.customer || null, {
            transaction,
        });
        
        await payments.setSupplier( data.supplier || null, {
            transaction,
        });
        
        await payments.setInvoice( data.invoice || null, {
            transaction,
        });
        
        await payments.setVendor_bill( data.vendor_bill || null, {
            transaction,
        });
        
        await payments.setPosted_journal_entry( data.posted_journal_entry || null, {
            transaction,
        });
        
        await payments.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

        

        return 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 paymentsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                payment_number: item.payment_number
            ||
            null
            ,
            
                direction: item.direction
            ||
            null
            ,
            
                counterparty_type: item.counterparty_type
            ||
            null
            ,
            
                paid_at: item.paid_at
            ||
            null
            ,
            
                amount: item.amount
            ||
            null
            ,
            
                currency: item.currency
            ||
            null
            ,
            
                method: item.method
            ||
            null
            ,
            
                reference: item.reference
            ||
            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 payments = await db.payments.bulkCreate(paymentsData, { transaction });

        // For each item created, replace relation files
        

        return payments;
    }

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


        

        const updatePayload = {};
        
        if (data.payment_number !== undefined) updatePayload.payment_number = data.payment_number;
        
        
        if (data.direction !== undefined) updatePayload.direction = data.direction;
        
        
        if (data.counterparty_type !== undefined) updatePayload.counterparty_type = data.counterparty_type;
        
        
        if (data.paid_at !== undefined) updatePayload.paid_at = data.paid_at;
        
        
        if (data.amount !== undefined) updatePayload.amount = data.amount;
        
        
        if (data.currency !== undefined) updatePayload.currency = data.currency;
        
        
        if (data.method !== undefined) updatePayload.method = data.method;
        
        
        if (data.reference !== undefined) updatePayload.reference = data.reference;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.tenant !== undefined) {
            await payments.setTenant(
              
              data.tenant,
              
              { transaction }
            );
        }
        
        if (data.customer !== undefined) {
            await payments.setCustomer(
              
              data.customer,
              
              { transaction }
            );
        }
        
        if (data.supplier !== undefined) {
            await payments.setSupplier(
              
              data.supplier,
              
              { transaction }
            );
        }
        
        if (data.invoice !== undefined) {
            await payments.setInvoice(
              
              data.invoice,
              
              { transaction }
            );
        }
        
        if (data.vendor_bill !== undefined) {
            await payments.setVendor_bill(
              
              data.vendor_bill,
              
              { transaction }
            );
        }
        
        if (data.posted_journal_entry !== undefined) {
            await payments.setPosted_journal_entry(
              
              data.posted_journal_entry,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await payments.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        

        

        return payments;
    }

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

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

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


        return payments;
    }

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

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

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

        await payments.destroy({
            transaction
        });

        return payments;
    }

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

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

        if (!payments) {
            return payments;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.tenant = await payments.getTenant({
            transaction
        });
        
        
        output.customer = await payments.getCustomer({
            transaction
        });
        
        
        output.supplier = await payments.getSupplier({
            transaction
        });
        
        
        output.invoice = await payments.getInvoice({
            transaction
        });
        
        
        output.vendor_bill = await payments.getVendor_bill({
            transaction
        });
        
        
        output.posted_journal_entry = await payments.getPosted_journal_entry({
            transaction
        });
        
        
        output.organizations = await payments.getOrganizations({
            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 userOrganizations = (user && user.organizations?.id) || null;
        

        
        if (userOrganizations) {
            if (options?.currentUser?.organizationsId) {
                where.organizationsId = options.currentUser.organizationsId;
            }
        }
        

        offset = currentPage * limit;

        const orderBy = null;

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

    let include = [

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

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

      {
        model: db.suppliers,
        as: 'supplier',
        
        where: filter.supplier ? {
          [Op.or]: [
            { id: { [Op.in]: filter.supplier.split('|').map(term => Utils.uuid(term)) } },
            {
              name: {
                [Op.or]: filter.supplier.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_number: {
                [Op.or]: filter.invoice.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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

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

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



    ];

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

            
            if (filter.payment_number) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'payments',
                        'payment_number',
                        filter.payment_number,
                    ),
                };
            }
            
            if (filter.currency) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'payments',
                        'currency',
                        filter.currency,
                    ),
                };
            }
            
            if (filter.reference) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'payments',
                        'reference',
                        filter.reference,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

            
            if (filter.direction) {
                where = {
                    ...where,
                direction: filter.direction,
            };
            }
            
            if (filter.counterparty_type) {
                where = {
                    ...where,
                counterparty_type: filter.counterparty_type,
            };
            }
            
            if (filter.method) {
                where = {
                    ...where,
                method: filter.method,
            };
            }
            
            if (filter.status) {
                where = {
                    ...where,
                status: filter.status,
            };
            }
            


      

      

      

      

      

      

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

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

        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.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,  globalAccess, organizationId,) {
        let where = {};
        
        
        if (!globalAccess && organizationId) {
            where.organizationId = organizationId;
        }
        

        if (query) {
            where = {
                [Op.or]: [
                    { ['id']: Utils.uuid(query) },
                    Utils.ilike(
                        'payments',
                        'payment_number',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

