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

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

        const cost_items = await db.cost_items.create(
            {
                id: data.id || undefined,
        
        category: data.category
        ||
        null
            ,
            
        occurred_at: data.occurred_at
        ||
        null
            ,
            
        amount: data.amount
        ||
        null
            ,
            
        currency: data.currency
        ||
        null
            ,
            
        vendor: data.vendor
        ||
        null
            ,
            
        reference: data.reference
        ||
        null
            ,
            
        notes: data.notes
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await cost_items.setCompany( data.company || null, {
            transaction,
        });
        
        await cost_items.setTrip( data.trip || null, {
            transaction,
        });
        
        await cost_items.setVehicle( data.vehicle || null, {
            transaction,
        });
        
        await cost_items.setTrailer( data.trailer || null, {
            transaction,
        });
        
        await cost_items.setEmployee( data.employee || null, {
            transaction,
        });
        
        await cost_items.setLoad( data.load || null, {
            transaction,
        });
        
        await cost_items.setVendor_rel( data.vendor_rel || null, {
            transaction,
        });
        
        await cost_items.setFuel_entry( data.fuel_entry || null, {
            transaction,
        });
        
        await cost_items.setToll_entry( data.toll_entry || null, {
            transaction,
        });
        

        

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

        return cost_items;
    }
    

    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 cost_itemsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                category: item.category
            ||
            null
            ,
            
                occurred_at: item.occurred_at
            ||
            null
            ,
            
                amount: item.amount
            ||
            null
            ,
            
                currency: item.currency
            ||
            null
            ,
            
                vendor: item.vendor
            ||
            null
            ,
            
                reference: item.reference
            ||
            null
            ,
            
                notes: item.notes
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

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

        return cost_items;
    }

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

        const cost_items = await db.cost_items.findByPk(id, {}, {transaction});


        

        const updatePayload = {};
        
        if (data.category !== undefined) updatePayload.category = data.category;
        
        
        if (data.occurred_at !== undefined) updatePayload.occurred_at = data.occurred_at;
        
        
        if (data.amount !== undefined) updatePayload.amount = data.amount;
        
        
        if (data.currency !== undefined) updatePayload.currency = data.currency;
        
        
        if (data.vendor !== undefined) updatePayload.vendor = data.vendor;
        
        
        if (data.reference !== undefined) updatePayload.reference = data.reference;
        
        
        if (data.notes !== undefined) updatePayload.notes = data.notes;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.company !== undefined) {
            await cost_items.setCompany(
              
              data.company,
              
              { transaction }
            );
        }
        
        if (data.trip !== undefined) {
            await cost_items.setTrip(
              
              data.trip,
              
              { transaction }
            );
        }
        
        if (data.vehicle !== undefined) {
            await cost_items.setVehicle(
              
              data.vehicle,
              
              { transaction }
            );
        }
        
        if (data.trailer !== undefined) {
            await cost_items.setTrailer(
              
              data.trailer,
              
              { transaction }
            );
        }
        
        if (data.employee !== undefined) {
            await cost_items.setEmployee(
              
              data.employee,
              
              { transaction }
            );
        }
        
        if (data.load !== undefined) {
            await cost_items.setLoad(
              
              data.load,
              
              { transaction }
            );
        }
        
        if (data.vendor_rel !== undefined) {
            await cost_items.setVendor_rel(
              
              data.vendor_rel,
              
              { transaction }
            );
        }
        
        if (data.fuel_entry !== undefined) {
            await cost_items.setFuel_entry(
              
              data.fuel_entry,
              
              { transaction }
            );
        }
        
        if (data.toll_entry !== undefined) {
            await cost_items.setToll_entry(
              
              data.toll_entry,
              
              { transaction }
            );
        }
        

        
        

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

        return cost_items;
    }

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

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

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


        return cost_items;
    }

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

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

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

        await cost_items.destroy({
            transaction
        });

        return cost_items;
    }

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

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

        if (!cost_items) {
            return cost_items;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.invoice_lines_cost_item = await cost_items.getInvoice_lines_cost_item({
            transaction
        });
        
        
        
        
        output.cost_files_cost_item = await cost_items.getCost_files_cost_item({
            transaction
        });
        
        
        output.fuel_entries_cost_item = await cost_items.getFuel_entries_cost_item({
            transaction
        });
        
        
        output.toll_entries_cost_item = await cost_items.getToll_entries_cost_item({
            transaction
        });
        
        
        
        output.company = await cost_items.getCompany({
            transaction
        });
        
        
        output.trip = await cost_items.getTrip({
            transaction
        });
        
        
        output.vehicle = await cost_items.getVehicle({
            transaction
        });
        
        
        output.trailer = await cost_items.getTrailer({
            transaction
        });
        
        
        output.employee = await cost_items.getEmployee({
            transaction
        });
        
        
        output.load = await cost_items.getLoad({
            transaction
        });
        
        
        output.vendor_rel = await cost_items.getVendor_rel({
            transaction
        });
        
        
        output.receipt = await cost_items.getReceipt({
            transaction
        });
        
        
        output.fuel_entry = await cost_items.getFuel_entry({
            transaction
        });
        
        
        output.toll_entry = await cost_items.getToll_entry({
            transaction
        });
        
        

        return output;
    }

    static async findAll(
          filter,
           options
        ) {
        const limit = filter.limit || 0;
        let offset = 0;
        let where = {};
        const currentPage = +filter.page;

        

        

        offset = currentPage * limit;

        const orderBy = null;

    const transaction = (options && options.transaction) || undefined;

    let include = [

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

      {
        model: db.trips,
        as: 'trip',
        
        where: filter.trip ? {
          [Op.or]: [
            { id: { [Op.in]: filter.trip.split('|').map(term => Utils.uuid(term)) } },
            {
              trip_no: {
                [Op.or]: filter.trip.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_number: {
                [Op.or]: filter.vehicle.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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

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

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

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

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

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



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

    ];

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

            
            if (filter.vendor) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'cost_items',
                        'vendor',
                        filter.vendor,
                    ),
                };
            }
            
            if (filter.reference) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'cost_items',
                        'reference',
                        filter.reference,
                    ),
                };
            }
            
            if (filter.notes) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'cost_items',
                        'notes',
                        filter.notes,
                    ),
                };
            }
            

            
            

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

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

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


      

      

      

      

      

      

      

      

      



            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,
                        },
                    };
                }
            }
        }
        

        

        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.cost_items.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, ) {
        let where = {};
        
        

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

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

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

    
};

