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

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

        const invoice_lines = await db.invoice_lines.create(
            {
                id: data.id || undefined,
        
        line_type: data.line_type
        ||
        null
            ,
            
        description: data.description
        ||
        null
            ,
            
        quantity: data.quantity
        ||
        null
            ,
            
        rate: data.rate
        ||
        null
            ,
            
        amount: data.amount
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await invoice_lines.setInvoice( data.invoice || null, {
            transaction,
        });
        
        await invoice_lines.setVehicle( data.vehicle || null, {
            transaction,
        });
        
        await invoice_lines.setRevenue_account( data.revenue_account || null, {
            transaction,
        });
        
        await invoice_lines.setCompanies( data.companies || null, {
            transaction,
        });
        

        

        

        return invoice_lines;
    }
    

    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 invoice_linesData = data.map((item, index) => ({
                id: item.id || undefined,
                
                line_type: item.line_type
            ||
            null
            ,
            
                description: item.description
            ||
            null
            ,
            
                quantity: item.quantity
            ||
            null
            ,
            
                rate: item.rate
            ||
            null
            ,
            
                amount: item.amount
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return invoice_lines;
    }

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


        

        const updatePayload = {};
        
        if (data.line_type !== undefined) updatePayload.line_type = data.line_type;
        
        
        if (data.description !== undefined) updatePayload.description = data.description;
        
        
        if (data.quantity !== undefined) updatePayload.quantity = data.quantity;
        
        
        if (data.rate !== undefined) updatePayload.rate = data.rate;
        
        
        if (data.amount !== undefined) updatePayload.amount = data.amount;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.invoice !== undefined) {
            await invoice_lines.setInvoice(
              
              data.invoice,
              
              { transaction }
            );
        }
        
        if (data.vehicle !== undefined) {
            await invoice_lines.setVehicle(
              
              data.vehicle,
              
              { transaction }
            );
        }
        
        if (data.revenue_account !== undefined) {
            await invoice_lines.setRevenue_account(
              
              data.revenue_account,
              
              { transaction }
            );
        }
        
        if (data.companies !== undefined) {
            await invoice_lines.setCompanies(
              
              data.companies,
              
              { transaction }
            );
        }
        

        
        

        

        return invoice_lines;
    }

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

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

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


        return invoice_lines;
    }

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

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

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

        await invoice_lines.destroy({
            transaction
        });

        return invoice_lines;
    }

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

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

        if (!invoice_lines) {
            return invoice_lines;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.invoice = await invoice_lines.getInvoice({
            transaction
        });
        
        
        output.vehicle = await invoice_lines.getVehicle({
            transaction
        });
        
        
        output.revenue_account = await invoice_lines.getRevenue_account({
            transaction
        });
        
        
        output.companies = await invoice_lines.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.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.vehicles,
        as: 'vehicle',
        
        where: filter.vehicle ? {
          [Op.or]: [
            { id: { [Op.in]: filter.vehicle.split('|').map(term => Utils.uuid(term)) } },
            {
              plate_no: {
                [Op.or]: filter.vehicle.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

      {
        model: db.chart_of_accounts,
        as: 'revenue_account',
        
        where: filter.revenue_account ? {
          [Op.or]: [
            { id: { [Op.in]: filter.revenue_account.split('|').map(term => Utils.uuid(term)) } },
            {
              account_name: {
                [Op.or]: filter.revenue_account.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.description) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'invoice_lines',
                        'description',
                        filter.description,
                    ),
                };
            }
            

            
            

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

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

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

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

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


      

      

      

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

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

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

    
};

