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

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

        const fuel_entries = await db.fuel_entries.create(
            {
                id: data.id || undefined,
        
        liters: data.liters
        ||
        null
            ,
            
        unit: data.unit
        ||
        null
            ,
            
        price_per_unit: data.price_per_unit
        ||
        null
            ,
            
        odometer_km: data.odometer_km
        ||
        null
            ,
            
        station_name: data.station_name
        ||
        null
            ,
            
        station_country_code: data.station_country_code
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await fuel_entries.setCost_item( data.cost_item || null, {
            transaction,
        });
        

        

        

        return fuel_entries;
    }
    

    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 fuel_entriesData = data.map((item, index) => ({
                id: item.id || undefined,
                
                liters: item.liters
            ||
            null
            ,
            
                unit: item.unit
            ||
            null
            ,
            
                price_per_unit: item.price_per_unit
            ||
            null
            ,
            
                odometer_km: item.odometer_km
            ||
            null
            ,
            
                station_name: item.station_name
            ||
            null
            ,
            
                station_country_code: item.station_country_code
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return fuel_entries;
    }

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

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


        

        const updatePayload = {};
        
        if (data.liters !== undefined) updatePayload.liters = data.liters;
        
        
        if (data.unit !== undefined) updatePayload.unit = data.unit;
        
        
        if (data.price_per_unit !== undefined) updatePayload.price_per_unit = data.price_per_unit;
        
        
        if (data.odometer_km !== undefined) updatePayload.odometer_km = data.odometer_km;
        
        
        if (data.station_name !== undefined) updatePayload.station_name = data.station_name;
        
        
        if (data.station_country_code !== undefined) updatePayload.station_country_code = data.station_country_code;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.cost_item !== undefined) {
            await fuel_entries.setCost_item(
              
              data.cost_item,
              
              { transaction }
            );
        }
        

        
        

        

        return fuel_entries;
    }

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

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

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


        return fuel_entries;
    }

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

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

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

        await fuel_entries.destroy({
            transaction
        });

        return fuel_entries;
    }

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

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

        if (!fuel_entries) {
            return fuel_entries;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.cost_items_fuel_entry = await fuel_entries.getCost_items_fuel_entry({
            transaction
        });
        
        
        
        
        
        
        output.cost_item = await fuel_entries.getCost_item({
            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.cost_items,
        as: 'cost_item',
        
        where: filter.cost_item ? {
          [Op.or]: [
            { id: { [Op.in]: filter.cost_item.split('|').map(term => Utils.uuid(term)) } },
            {
              reference: {
                [Op.or]: filter.cost_item.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },



    ];

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

            
            if (filter.station_name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'fuel_entries',
                        'station_name',
                        filter.station_name,
                    ),
                };
            }
            
            if (filter.station_country_code) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'fuel_entries',
                        'station_country_code',
                        filter.station_country_code,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    odometer_km: {
                    ...where.odometer_km,
                            [Op.lte]: end,
                    },
                };
                }
            }
            

            if (filter.active !== undefined) {
                where = {
                    ...where,
                    active: filter.active === true || filter.active === 'true'
                };
            }

            
            if (filter.unit) {
                where = {
                    ...where,
                unit: filter.unit,
            };
            }
            


      



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

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

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

    
};

