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

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

        const vehicles = await db.vehicles.create(
            {
                id: data.id || undefined,
        
        display_name: data.display_name
        ||
        null
            ,
            
        make: data.make
        ||
        null
            ,
            
        model: data.model
        ||
        null
            ,
            
        year_label: data.year_label
        ||
        null
            ,
            
        vin: data.vin
        ||
        null
            ,
            
        license_plate: data.license_plate
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        odometer_km: data.odometer_km
        ||
        null
            ,
            
        fuel_policy: data.fuel_policy
        ||
        null
            ,
            
        color: data.color
        ||
        null
            ,
            
        features: data.features
        ||
        null
            ,
            
        next_service_at: data.next_service_at
        ||
        null
            ,
            
        is_listed: data.is_listed
        ||
        false
        
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await vehicles.setCompany( data.company || null, {
            transaction,
        });
        
        await vehicles.setBranch( data.branch || null, {
            transaction,
        });
        
        await vehicles.setCategory( data.category || null, {
            transaction,
        });
        
        await vehicles.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

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

        return vehicles;
    }
    

    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 vehiclesData = data.map((item, index) => ({
                id: item.id || undefined,
                
                display_name: item.display_name
            ||
            null
            ,
            
                make: item.make
            ||
            null
            ,
            
                model: item.model
            ||
            null
            ,
            
                year_label: item.year_label
            ||
            null
            ,
            
                vin: item.vin
            ||
            null
            ,
            
                license_plate: item.license_plate
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
                odometer_km: item.odometer_km
            ||
            null
            ,
            
                fuel_policy: item.fuel_policy
            ||
            null
            ,
            
                color: item.color
            ||
            null
            ,
            
                features: item.features
            ||
            null
            ,
            
                next_service_at: item.next_service_at
            ||
            null
            ,
            
                is_listed: item.is_listed
            ||
            false
        
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

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

        return vehicles;
    }

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


        

        const updatePayload = {};
        
        if (data.display_name !== undefined) updatePayload.display_name = data.display_name;
        
        
        if (data.make !== undefined) updatePayload.make = data.make;
        
        
        if (data.model !== undefined) updatePayload.model = data.model;
        
        
        if (data.year_label !== undefined) updatePayload.year_label = data.year_label;
        
        
        if (data.vin !== undefined) updatePayload.vin = data.vin;
        
        
        if (data.license_plate !== undefined) updatePayload.license_plate = data.license_plate;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.odometer_km !== undefined) updatePayload.odometer_km = data.odometer_km;
        
        
        if (data.fuel_policy !== undefined) updatePayload.fuel_policy = data.fuel_policy;
        
        
        if (data.color !== undefined) updatePayload.color = data.color;
        
        
        if (data.features !== undefined) updatePayload.features = data.features;
        
        
        if (data.next_service_at !== undefined) updatePayload.next_service_at = data.next_service_at;
        
        
        if (data.is_listed !== undefined) updatePayload.is_listed = data.is_listed;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.company !== undefined) {
            await vehicles.setCompany(
              
              data.company,
              
              { transaction }
            );
        }
        
        if (data.branch !== undefined) {
            await vehicles.setBranch(
              
              data.branch,
              
              { transaction }
            );
        }
        
        if (data.category !== undefined) {
            await vehicles.setCategory(
              
              data.category,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await vehicles.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        

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

        return vehicles;
    }

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

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

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


        return vehicles;
    }

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

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

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

        await vehicles.destroy({
            transaction
        });

        return vehicles;
    }

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

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

        if (!vehicles) {
            return vehicles;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.bookings_vehicle = await vehicles.getBookings_vehicle({
            transaction
        });
        
        
        
        
        
        
        
        output.tasks_vehicle = await vehicles.getTasks_vehicle({
            transaction
        });
        
        
        output.maintenance_records_vehicle = await vehicles.getMaintenance_records_vehicle({
            transaction
        });
        
        
        
        
        
        output.company = await vehicles.getCompany({
            transaction
        });
        
        
        output.branch = await vehicles.getBranch({
            transaction
        });
        
        
        output.category = await vehicles.getCategory({
            transaction
        });
        
        
        output.photos = await vehicles.getPhotos({
            transaction
        });
        
        
        output.organizations = await vehicles.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.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.branches,
        as: 'branch',
        
        where: filter.branch ? {
          [Op.or]: [
            { id: { [Op.in]: filter.branch.split('|').map(term => Utils.uuid(term)) } },
            {
              name: {
                [Op.or]: filter.branch.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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

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



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

    ];

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

            
            if (filter.display_name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'vehicles',
                        'display_name',
                        filter.display_name,
                    ),
                };
            }
            
            if (filter.make) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'vehicles',
                        'make',
                        filter.make,
                    ),
                };
            }
            
            if (filter.model) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'vehicles',
                        'model',
                        filter.model,
                    ),
                };
            }
            
            if (filter.year_label) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'vehicles',
                        'year_label',
                        filter.year_label,
                    ),
                };
            }
            
            if (filter.vin) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'vehicles',
                        'vin',
                        filter.vin,
                    ),
                };
            }
            
            if (filter.license_plate) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'vehicles',
                        'license_plate',
                        filter.license_plate,
                    ),
                };
            }
            
            if (filter.color) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'vehicles',
                        'color',
                        filter.color,
                    ),
                };
            }
            
            if (filter.features) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'vehicles',
                        'features',
                        filter.features,
                    ),
                };
            }
            

            
            

            
            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.next_service_atRange) {
                const [start, end] = filter.next_service_atRange;

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

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


      

      

      

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

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

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

    
};

