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

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

        const vehicle_categories = await db.vehicle_categories.create(
            {
                id: data.id || undefined,
        
        name: data.name
        ||
        null
            ,
            
        description: data.description
        ||
        null
            ,
            
        transmission: data.transmission
        ||
        null
            ,
            
        fuel_type: data.fuel_type
        ||
        null
            ,
            
        seats: data.seats
        ||
        null
            ,
            
        doors: data.doors
        ||
        null
            ,
            
        large_bags: data.large_bags
        ||
        null
            ,
            
        small_bags: data.small_bags
        ||
        null
            ,
            
        has_air_conditioning: data.has_air_conditioning
        ||
        false
        
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await vehicle_categories.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

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

        return vehicle_categories;
    }
    

    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 vehicle_categoriesData = data.map((item, index) => ({
                id: item.id || undefined,
                
                name: item.name
            ||
            null
            ,
            
                description: item.description
            ||
            null
            ,
            
                transmission: item.transmission
            ||
            null
            ,
            
                fuel_type: item.fuel_type
            ||
            null
            ,
            
                seats: item.seats
            ||
            null
            ,
            
                doors: item.doors
            ||
            null
            ,
            
                large_bags: item.large_bags
            ||
            null
            ,
            
                small_bags: item.small_bags
            ||
            null
            ,
            
                has_air_conditioning: item.has_air_conditioning
            ||
            false
        
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

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

        return vehicle_categories;
    }

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


        

        const updatePayload = {};
        
        if (data.name !== undefined) updatePayload.name = data.name;
        
        
        if (data.description !== undefined) updatePayload.description = data.description;
        
        
        if (data.transmission !== undefined) updatePayload.transmission = data.transmission;
        
        
        if (data.fuel_type !== undefined) updatePayload.fuel_type = data.fuel_type;
        
        
        if (data.seats !== undefined) updatePayload.seats = data.seats;
        
        
        if (data.doors !== undefined) updatePayload.doors = data.doors;
        
        
        if (data.large_bags !== undefined) updatePayload.large_bags = data.large_bags;
        
        
        if (data.small_bags !== undefined) updatePayload.small_bags = data.small_bags;
        
        
        if (data.has_air_conditioning !== undefined) updatePayload.has_air_conditioning = data.has_air_conditioning;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.organizations !== undefined) {
            await vehicle_categories.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        

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

        return vehicle_categories;
    }

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

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

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


        return vehicle_categories;
    }

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

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

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

        await vehicle_categories.destroy({
            transaction
        });

        return vehicle_categories;
    }

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

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

        if (!vehicle_categories) {
            return vehicle_categories;
        }

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

        
        
        
        
        
        
        
        
        output.vehicles_category = await vehicle_categories.getVehicles_category({
            transaction
        });
        
        
        
        output.rate_rules_category = await vehicle_categories.getRate_rules_category({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.image = await vehicle_categories.getImage({
            transaction
        });
        
        
        output.organizations = await vehicle_categories.getOrganizations({
            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 userOrganizations = (user && user.organizations?.id) || null;
        

        
        if (userOrganizations) {
            if (options?.currentUser?.organizationsId) {
                where.organizationsId = options.currentUser.organizationsId;
            }
        }
        

        offset = currentPage * limit;

        const orderBy = null;

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

    let include = [

      {
        model: db.organizations,
        as: 'organizations',
        
      },



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

    ];

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

            
            if (filter.name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'vehicle_categories',
                        'name',
                        filter.name,
                    ),
                };
            }
            
            if (filter.description) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'vehicle_categories',
                        'description',
                        filter.description,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

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

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

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

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

            
            if (filter.transmission) {
                where = {
                    ...where,
                transmission: filter.transmission,
            };
            }
            
            if (filter.fuel_type) {
                where = {
                    ...where,
                fuel_type: filter.fuel_type,
            };
            }
            
            if (filter.has_air_conditioning) {
                where = {
                    ...where,
                has_air_conditioning: filter.has_air_conditioning,
            };
            }
            


      
      if (filter.organizations) {
        const listItems = filter.organizations.split('|').map(item => {
          return  Utils.uuid(item)
        });

        where = {
          ...where,
          organizationsId: {[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.organizationsId;
        }
        

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

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

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

    
};

