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

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

        const supplier_invoices = await db.supplier_invoices.create(
            {
                id: data.id || undefined,
        
        invoice_number: data.invoice_number
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        matching_status: data.matching_status
        ||
        null
            ,
            
        invoice_date: data.invoice_date
        ||
        null
            ,
            
        due_at: data.due_at
        ||
        null
            ,
            
        subtotal: data.subtotal
        ||
        null
            ,
            
        tax_total: data.tax_total
        ||
        null
            ,
            
        total_amount: data.total_amount
        ||
        null
            ,
            
        amount_paid: data.amount_paid
        ||
        null
            ,
            
        attachment_note: data.attachment_note
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await supplier_invoices.setSupplier( data.supplier || null, {
            transaction,
        });
        
        await supplier_invoices.setPurchase_order( data.purchase_order || null, {
            transaction,
        });
        
        await supplier_invoices.setGoods_receipt( data.goods_receipt || null, {
            transaction,
        });
        
        await supplier_invoices.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

        
        await FileDBApi.replaceRelationFiles(
            {
                belongsTo: db.supplier_invoices.getTableName(),
                belongsToColumn: 'attachments',
                belongsToId: supplier_invoices.id,
            },
            data.attachments,
            options,
        );
        

        return supplier_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 supplier_invoicesData = data.map((item, index) => ({
                id: item.id || undefined,
                
                invoice_number: item.invoice_number
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
                matching_status: item.matching_status
            ||
            null
            ,
            
                invoice_date: item.invoice_date
            ||
            null
            ,
            
                due_at: item.due_at
            ||
            null
            ,
            
                subtotal: item.subtotal
            ||
            null
            ,
            
                tax_total: item.tax_total
            ||
            null
            ,
            
                total_amount: item.total_amount
            ||
            null
            ,
            
                amount_paid: item.amount_paid
            ||
            null
            ,
            
                attachment_note: item.attachment_note
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        
        for (let i = 0; i < supplier_invoices.length; i++) {
            await FileDBApi.replaceRelationFiles(
                {
                    belongsTo: db.supplier_invoices.getTableName(),
                    belongsToColumn: 'attachments',
                    belongsToId: supplier_invoices[i].id,
                },
                data[i].attachments,
                options,
            );
        }
        

        return supplier_invoices;
    }

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


        

        const updatePayload = {};
        
        if (data.invoice_number !== undefined) updatePayload.invoice_number = data.invoice_number;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.matching_status !== undefined) updatePayload.matching_status = data.matching_status;
        
        
        if (data.invoice_date !== undefined) updatePayload.invoice_date = data.invoice_date;
        
        
        if (data.due_at !== undefined) updatePayload.due_at = data.due_at;
        
        
        if (data.subtotal !== undefined) updatePayload.subtotal = data.subtotal;
        
        
        if (data.tax_total !== undefined) updatePayload.tax_total = data.tax_total;
        
        
        if (data.total_amount !== undefined) updatePayload.total_amount = data.total_amount;
        
        
        if (data.amount_paid !== undefined) updatePayload.amount_paid = data.amount_paid;
        
        
        if (data.attachment_note !== undefined) updatePayload.attachment_note = data.attachment_note;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.supplier !== undefined) {
            await supplier_invoices.setSupplier(
              
              data.supplier,
              
              { transaction }
            );
        }
        
        if (data.purchase_order !== undefined) {
            await supplier_invoices.setPurchase_order(
              
              data.purchase_order,
              
              { transaction }
            );
        }
        
        if (data.goods_receipt !== undefined) {
            await supplier_invoices.setGoods_receipt(
              
              data.goods_receipt,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await supplier_invoices.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        

        
        await FileDBApi.replaceRelationFiles(
            {
                belongsTo: db.supplier_invoices.getTableName(),
                belongsToColumn: 'attachments',
                belongsToId: supplier_invoices.id,
            },
            data.attachments,
            options,
        );
        

        return supplier_invoices;
    }

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

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

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


        return supplier_invoices;
    }

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

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

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

        await supplier_invoices.destroy({
            transaction
        });

        return supplier_invoices;
    }

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

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

        if (!supplier_invoices) {
            return supplier_invoices;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.supplier = await supplier_invoices.getSupplier({
            transaction
        });
        
        
        output.purchase_order = await supplier_invoices.getPurchase_order({
            transaction
        });
        
        
        output.goods_receipt = await supplier_invoices.getGoods_receipt({
            transaction
        });
        
        
        output.attachments = await supplier_invoices.getAttachments({
            transaction
        });
        
        
        output.organizations = await supplier_invoices.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.suppliers,
        as: 'supplier',
        
        where: filter.supplier ? {
          [Op.or]: [
            { id: { [Op.in]: filter.supplier.split('|').map(term => Utils.uuid(term)) } },
            {
              supplier_name: {
                [Op.or]: filter.supplier.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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

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

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



      {
        model: db.file,
        as: 'attachments',
      },

    ];

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

            
            if (filter.invoice_number) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'supplier_invoices',
                        'invoice_number',
                        filter.invoice_number,
                    ),
                };
            }
            
            if (filter.attachment_note) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'supplier_invoices',
                        'attachment_note',
                        filter.attachment_note,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

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

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

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

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

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

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    amount_paid: {
                    ...where.amount_paid,
                            [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.matching_status) {
                where = {
                    ...where,
                matching_status: filter.matching_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.supplier_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,  globalAccess, organizationId,) {
        let where = {};
        
        
        if (!globalAccess && organizationId) {
            where.organizationId = organizationId;
        }
        

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

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

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

    
};

