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

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

        const bills = await db.bills.create(
            {
                id: data.id || undefined,
        
        bill_no: data.bill_no
        ||
        null
            ,
            
        bill_date: data.bill_date
        ||
        null
            ,
            
        due_date: data.due_date
        ||
        null
            ,
            
        gross_amount: data.gross_amount
        ||
        null
            ,
            
        amount_paid: data.amount_paid
        ||
        null
            ,
            
        balance_due: data.balance_due
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await bills.setCompany( data.company || null, {
            transaction,
        });
        
        await bills.setVendor( data.vendor || null, {
            transaction,
        });
        
        await bills.setVehicle( data.vehicle || null, {
            transaction,
        });
        

        

        

        return bills;
    }
    

    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 billsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                bill_no: item.bill_no
            ||
            null
            ,
            
                bill_date: item.bill_date
            ||
            null
            ,
            
                due_date: item.due_date
            ||
            null
            ,
            
                gross_amount: item.gross_amount
            ||
            null
            ,
            
                amount_paid: item.amount_paid
            ||
            null
            ,
            
                balance_due: item.balance_due
            ||
            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 bills = await db.bills.bulkCreate(billsData, { transaction });

        // For each item created, replace relation files
        

        return bills;
    }

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


        

        const updatePayload = {};
        
        if (data.bill_no !== undefined) updatePayload.bill_no = data.bill_no;
        
        
        if (data.bill_date !== undefined) updatePayload.bill_date = data.bill_date;
        
        
        if (data.due_date !== undefined) updatePayload.due_date = data.due_date;
        
        
        if (data.gross_amount !== undefined) updatePayload.gross_amount = data.gross_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;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.company !== undefined) {
            await bills.setCompany(
              
              data.company,
              
              { transaction }
            );
        }
        
        if (data.vendor !== undefined) {
            await bills.setVendor(
              
              data.vendor,
              
              { transaction }
            );
        }
        
        if (data.vehicle !== undefined) {
            await bills.setVehicle(
              
              data.vehicle,
              
              { transaction }
            );
        }
        

        
        

        

        return bills;
    }

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

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

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


        return bills;
    }

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

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

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

        await bills.destroy({
            transaction
        });

        return bills;
    }

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

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

        if (!bills) {
            return bills;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.bill_lines_bill = await bills.getBill_lines_bill({
            transaction
        });
        
        
        output.bill_payments_bill = await bills.getBill_payments_bill({
            transaction
        });
        
        
        output.ledger_entries_bill = await bills.getLedger_entries_bill({
            transaction
        });
        
        
        
        
        
        
        
        output.company = await bills.getCompany({
            transaction
        });
        
        
        output.vendor = await bills.getVendor({
            transaction
        });
        
        
        output.vehicle = await bills.getVehicle({
            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.vendors,
        as: 'vendor',
        
        where: filter.vendor ? {
          [Op.or]: [
            { id: { [Op.in]: filter.vendor.split('|').map(term => Utils.uuid(term)) } },
            {
              vendor_name: {
                [Op.or]: filter.vendor.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}%` }))
              }
            },
          ]
        } : {},
        
      },



    ];

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

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

            
            

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

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    bill_date: {
                    ...where.bill_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.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.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.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.bills.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(
                        'bills',
                        'bill_no',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

