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

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

        const sales_invoices = await db.sales_invoices.create(
            {
                id: data.id || undefined,
        
        invoice_number: data.invoice_number
        ||
        null
            ,
            
        invoice_date: data.invoice_date
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        vat_treatment: data.vat_treatment
        ||
        null
            ,
            
        subtotal_amount: data.subtotal_amount
        ||
        null
            ,
            
        vat_amount: data.vat_amount
        ||
        null
            ,
            
        total_amount: data.total_amount
        ||
        null
            ,
            
        reviewed_at: data.reviewed_at
        ||
        null
            ,
            
        review_notes: data.review_notes
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await sales_invoices.setMerchant( data.merchant || null, {
            transaction,
        });
        
        await sales_invoices.setCustomer( data.customer || null, {
            transaction,
        });
        
        await sales_invoices.setReceipt( data.receipt || null, {
            transaction,
        });
        
        await sales_invoices.setEntered_by( data.entered_by || null, {
            transaction,
        });
        
        await sales_invoices.setReviewed_by( data.reviewed_by || null, {
            transaction,
        });
        
        await sales_invoices.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

        

        return sales_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 sales_invoicesData = data.map((item, index) => ({
                id: item.id || undefined,
                
                invoice_number: item.invoice_number
            ||
            null
            ,
            
                invoice_date: item.invoice_date
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
                vat_treatment: item.vat_treatment
            ||
            null
            ,
            
                subtotal_amount: item.subtotal_amount
            ||
            null
            ,
            
                vat_amount: item.vat_amount
            ||
            null
            ,
            
                total_amount: item.total_amount
            ||
            null
            ,
            
                reviewed_at: item.reviewed_at
            ||
            null
            ,
            
                review_notes: item.review_notes
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

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


        

        const updatePayload = {};
        
        if (data.invoice_number !== undefined) updatePayload.invoice_number = data.invoice_number;
        
        
        if (data.invoice_date !== undefined) updatePayload.invoice_date = data.invoice_date;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.vat_treatment !== undefined) updatePayload.vat_treatment = data.vat_treatment;
        
        
        if (data.subtotal_amount !== undefined) updatePayload.subtotal_amount = data.subtotal_amount;
        
        
        if (data.vat_amount !== undefined) updatePayload.vat_amount = data.vat_amount;
        
        
        if (data.total_amount !== undefined) updatePayload.total_amount = data.total_amount;
        
        
        if (data.reviewed_at !== undefined) updatePayload.reviewed_at = data.reviewed_at;
        
        
        if (data.review_notes !== undefined) updatePayload.review_notes = data.review_notes;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.merchant !== undefined) {
            await sales_invoices.setMerchant(
              
              data.merchant,
              
              { transaction }
            );
        }
        
        if (data.customer !== undefined) {
            await sales_invoices.setCustomer(
              
              data.customer,
              
              { transaction }
            );
        }
        
        if (data.receipt !== undefined) {
            await sales_invoices.setReceipt(
              
              data.receipt,
              
              { transaction }
            );
        }
        
        if (data.entered_by !== undefined) {
            await sales_invoices.setEntered_by(
              
              data.entered_by,
              
              { transaction }
            );
        }
        
        if (data.reviewed_by !== undefined) {
            await sales_invoices.setReviewed_by(
              
              data.reviewed_by,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await sales_invoices.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        

        

        return sales_invoices;
    }

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

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

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


        return sales_invoices;
    }

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

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

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

        await sales_invoices.destroy({
            transaction
        });

        return sales_invoices;
    }

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

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

        if (!sales_invoices) {
            return sales_invoices;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        output.sales_invoice_lines_sales_invoice = await sales_invoices.getSales_invoice_lines_sales_invoice({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        
        output.merchant = await sales_invoices.getMerchant({
            transaction
        });
        
        
        output.customer = await sales_invoices.getCustomer({
            transaction
        });
        
        
        output.receipt = await sales_invoices.getReceipt({
            transaction
        });
        
        
        output.entered_by = await sales_invoices.getEntered_by({
            transaction
        });
        
        
        output.reviewed_by = await sales_invoices.getReviewed_by({
            transaction
        });
        
        
        output.organizations = await sales_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.merchants,
        as: 'merchant',
        
        where: filter.merchant ? {
          [Op.or]: [
            { id: { [Op.in]: filter.merchant.split('|').map(term => Utils.uuid(term)) } },
            {
              business_name: {
                [Op.or]: filter.merchant.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.receipts,
        as: 'receipt',
        
        where: filter.receipt ? {
          [Op.or]: [
            { id: { [Op.in]: filter.receipt.split('|').map(term => Utils.uuid(term)) } },
            {
              source_channel: {
                [Op.or]: filter.receipt.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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

      {
        model: db.users,
        as: 'reviewed_by',
        
        where: filter.reviewed_by ? {
          [Op.or]: [
            { id: { [Op.in]: filter.reviewed_by.split('|').map(term => Utils.uuid(term)) } },
            {
              firstName: {
                [Op.or]: filter.reviewed_by.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.invoice_number) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'sales_invoices',
                        'invoice_number',
                        filter.invoice_number,
                    ),
                };
            }
            
            if (filter.review_notes) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'sales_invoices',
                        'review_notes',
                        filter.review_notes,
                    ),
                };
            }
            

            
            

            
            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.subtotal_amountRange) {
                const [start, end] = filter.subtotal_amountRange;

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

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

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    vat_amount: {
                    ...where.vat_amount,
                            [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.reviewed_atRange) {
                const [start, end] = filter.reviewed_atRange;

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    reviewed_at: {
                    ...where.reviewed_at,
                            [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.vat_treatment) {
                where = {
                    ...where,
                vat_treatment: filter.vat_treatment,
            };
            }
            


      

      

      

      

      

      
      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.sales_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(
                        'sales_invoices',
                        'invoice_number',
                        query,
                    ),
                ],
            };
        }

        const records = await db.sales_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,
        }));
    }

    
};

