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

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

        const toll_entries = await db.toll_entries.create(
            {
                id: data.id || undefined,
        
        country: data.country
        ||
        null
            ,
            
        provider: data.provider
        ||
        null
            ,
            
        toll_ref: data.toll_ref
        ||
        null
            ,
            
        route_hint: data.route_hint
        ||
        null
            ,
            
        entry_at: data.entry_at
        ||
        null
            ,
            
        exit_at: data.exit_at
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

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

        

        

        return toll_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 toll_entriesData = data.map((item, index) => ({
                id: item.id || undefined,
                
                country: item.country
            ||
            null
            ,
            
                provider: item.provider
            ||
            null
            ,
            
                toll_ref: item.toll_ref
            ||
            null
            ,
            
                route_hint: item.route_hint
            ||
            null
            ,
            
                entry_at: item.entry_at
            ||
            null
            ,
            
                exit_at: item.exit_at
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return toll_entries;
    }

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

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


        

        const updatePayload = {};
        
        if (data.country !== undefined) updatePayload.country = data.country;
        
        
        if (data.provider !== undefined) updatePayload.provider = data.provider;
        
        
        if (data.toll_ref !== undefined) updatePayload.toll_ref = data.toll_ref;
        
        
        if (data.route_hint !== undefined) updatePayload.route_hint = data.route_hint;
        
        
        if (data.entry_at !== undefined) updatePayload.entry_at = data.entry_at;
        
        
        if (data.exit_at !== undefined) updatePayload.exit_at = data.exit_at;
        
        
        updatePayload.updatedById = currentUser.id;

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

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

        
        

        

        return toll_entries;
    }

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

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

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


        return toll_entries;
    }

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

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

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

        await toll_entries.destroy({
            transaction
        });

        return toll_entries;
    }

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

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

        if (!toll_entries) {
            return toll_entries;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.cost_items_toll_entry = await toll_entries.getCost_items_toll_entry({
            transaction
        });
        
        
        
        
        
        
        output.cost_item = await toll_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.toll_ref) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'toll_entries',
                        'toll_ref',
                        filter.toll_ref,
                    ),
                };
            }
            
            if (filter.route_hint) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'toll_entries',
                        'route_hint',
                        filter.route_hint,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

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


      



            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.toll_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(
                        'toll_entries',
                        'toll_ref',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

