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

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

        const invoices = await db.invoices.create(
            {
                id: data.id || undefined,
        
        invoice_no: data.invoice_no
        ||
        null
            ,
            
        issue_date: data.issue_date
        ||
        null
            ,
            
        due_date: data.due_date
        ||
        null
            ,
            
        week_start: data.week_start
        ||
        null
            ,
            
        week_end: data.week_end
        ||
        null
            ,
            
        billing_days: data.billing_days
        ||
        null
            ,
            
        holiday_days: data.holiday_days
        ||
        null
            ,
            
        billable_days: data.billable_days
        ||
        null
            ,
            
        daily_rate: data.daily_rate
        ||
        null
            ,
            
        gross_amount: data.gross_amount
        ||
        null
            ,
            
        expense_deductions: data.expense_deductions
        ||
        null
            ,
            
        net_amount: data.net_amount
        ||
        null
            ,
            
        amount_paid: data.amount_paid
        ||
        null
            ,
            
        balance_due: data.balance_due
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        created_on: data.created_on
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await invoices.setCompany( data.company || null, {
            transaction,
        });
        
        await invoices.setDriver( data.driver || null, {
            transaction,
        });
        
        await invoices.setVehicle( data.vehicle || null, {
            transaction,
        });
        
        await invoices.setAgreement( data.agreement || null, {
            transaction,
        });
        

        

        

        return 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 invoicesData = data.map((item, index) => ({
                id: item.id || undefined,
                
                invoice_no: item.invoice_no
            ||
            null
            ,
            
                issue_date: item.issue_date
            ||
            null
            ,
            
                due_date: item.due_date
            ||
            null
            ,
            
                week_start: item.week_start
            ||
            null
            ,
            
                week_end: item.week_end
            ||
            null
            ,
            
                billing_days: item.billing_days
            ||
            null
            ,
            
                holiday_days: item.holiday_days
            ||
            null
            ,
            
                billable_days: item.billable_days
            ||
            null
            ,
            
                daily_rate: item.daily_rate
            ||
            null
            ,
            
                gross_amount: item.gross_amount
            ||
            null
            ,
            
                expense_deductions: item.expense_deductions
            ||
            null
            ,
            
                net_amount: item.net_amount
            ||
            null
            ,
            
                amount_paid: item.amount_paid
            ||
            null
            ,
            
                balance_due: item.balance_due
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
                created_on: item.created_on
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

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


        

        const updatePayload = {};
        
        if (data.invoice_no !== undefined) updatePayload.invoice_no = data.invoice_no;
        
        
        if (data.issue_date !== undefined) updatePayload.issue_date = data.issue_date;
        
        
        if (data.due_date !== undefined) updatePayload.due_date = data.due_date;
        
        
        if (data.week_start !== undefined) updatePayload.week_start = data.week_start;
        
        
        if (data.week_end !== undefined) updatePayload.week_end = data.week_end;
        
        
        if (data.billing_days !== undefined) updatePayload.billing_days = data.billing_days;
        
        
        if (data.holiday_days !== undefined) updatePayload.holiday_days = data.holiday_days;
        
        
        if (data.billable_days !== undefined) updatePayload.billable_days = data.billable_days;
        
        
        if (data.daily_rate !== undefined) updatePayload.daily_rate = data.daily_rate;
        
        
        if (data.gross_amount !== undefined) updatePayload.gross_amount = data.gross_amount;
        
        
        if (data.expense_deductions !== undefined) updatePayload.expense_deductions = data.expense_deductions;
        
        
        if (data.net_amount !== undefined) updatePayload.net_amount = data.net_amount;
        
        
        if (data.amount_paid !== undefined) updatePayload.amount_paid = data.amount_paid;
        
        
        if (data.balance_due !== undefined) updatePayload.balance_due = data.balance_due;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.created_on !== undefined) updatePayload.created_on = data.created_on;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.company !== undefined) {
            await invoices.setCompany(
              
              data.company,
              
              { transaction }
            );
        }
        
        if (data.driver !== undefined) {
            await invoices.setDriver(
              
              data.driver,
              
              { transaction }
            );
        }
        
        if (data.vehicle !== undefined) {
            await invoices.setVehicle(
              
              data.vehicle,
              
              { transaction }
            );
        }
        
        if (data.agreement !== undefined) {
            await invoices.setAgreement(
              
              data.agreement,
              
              { transaction }
            );
        }
        

        
        

        

        return invoices;
    }

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

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

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


        return invoices;
    }

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

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

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

        await invoices.destroy({
            transaction
        });

        return invoices;
    }

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

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

        if (!invoices) {
            return invoices;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        output.invoice_lines_invoice = await invoices.getInvoice_lines_invoice({
            transaction
        });
        
        
        
        output.payment_allocations_invoice = await invoices.getPayment_allocations_invoice({
            transaction
        });
        
        
        
        
        output.driver_expenses_invoice = await invoices.getDriver_expenses_invoice({
            transaction
        });
        
        
        
        
        
        output.ledger_entries_invoice = await invoices.getLedger_entries_invoice({
            transaction
        });
        
        
        
        
        
        
        
        output.company = await invoices.getCompany({
            transaction
        });
        
        
        output.driver = await invoices.getDriver({
            transaction
        });
        
        
        output.vehicle = await invoices.getVehicle({
            transaction
        });
        
        
        output.agreement = await invoices.getAgreement({
            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.companies,
        as: 'company',
        
      },

      {
        model: db.drivers,
        as: 'driver',
        
        where: filter.driver ? {
          [Op.or]: [
            { id: { [Op.in]: filter.driver.split('|').map(term => Utils.uuid(term)) } },
            {
              driver_name: {
                [Op.or]: filter.driver.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.agreements,
        as: 'agreement',
        
        where: filter.agreement ? {
          [Op.or]: [
            { id: { [Op.in]: filter.agreement.split('|').map(term => Utils.uuid(term)) } },
            {
              agreement_number: {
                [Op.or]: filter.agreement.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },



    ];

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

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

            
            

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    created_on: {
                    ...where.created_on,
                            [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.company) {
        const listItems = filter.company.split('|').map(item => {
          return  Utils.uuid(item)
        });

        where = {
          ...where,
          companyId: {[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.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(
                        'invoices',
                        'invoice_no',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

