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

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

        const maintenance_records = await db.maintenance_records.create(
            {
                id: data.id || undefined,
        
        maintenance_type: data.maintenance_type
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        start_at: data.start_at
        ||
        null
            ,
            
        end_at: data.end_at
        ||
        null
            ,
            
        odometer_km: data.odometer_km
        ||
        null
            ,
            
        cost_amount: data.cost_amount
        ||
        null
            ,
            
        currency: data.currency
        ||
        null
            ,
            
        notes: data.notes
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await maintenance_records.setVehicle( data.vehicle || null, {
            transaction,
        });
        
        await maintenance_records.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

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

        return maintenance_records;
    }
    

    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 maintenance_recordsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                maintenance_type: item.maintenance_type
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
                start_at: item.start_at
            ||
            null
            ,
            
                end_at: item.end_at
            ||
            null
            ,
            
                odometer_km: item.odometer_km
            ||
            null
            ,
            
                cost_amount: item.cost_amount
            ||
            null
            ,
            
                currency: item.currency
            ||
            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 maintenance_records = await db.maintenance_records.bulkCreate(maintenance_recordsData, { transaction });

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

        return maintenance_records;
    }

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


        

        const updatePayload = {};
        
        if (data.maintenance_type !== undefined) updatePayload.maintenance_type = data.maintenance_type;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.start_at !== undefined) updatePayload.start_at = data.start_at;
        
        
        if (data.end_at !== undefined) updatePayload.end_at = data.end_at;
        
        
        if (data.odometer_km !== undefined) updatePayload.odometer_km = data.odometer_km;
        
        
        if (data.cost_amount !== undefined) updatePayload.cost_amount = data.cost_amount;
        
        
        if (data.currency !== undefined) updatePayload.currency = data.currency;
        
        
        if (data.notes !== undefined) updatePayload.notes = data.notes;
        
        
        updatePayload.updatedById = currentUser.id;

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

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

        
        

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

        return maintenance_records;
    }

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

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

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


        return maintenance_records;
    }

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

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

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

        await maintenance_records.destroy({
            transaction
        });

        return maintenance_records;
    }

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

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

        if (!maintenance_records) {
            return maintenance_records;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.vehicle = await maintenance_records.getVehicle({
            transaction
        });
        
        
        output.attachments = await maintenance_records.getAttachments({
            transaction
        });
        
        
        output.organizations = await maintenance_records.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.vehicles,
        as: 'vehicle',
        
        where: filter.vehicle ? {
          [Op.or]: [
            { id: { [Op.in]: filter.vehicle.split('|').map(term => Utils.uuid(term)) } },
            {
              display_name: {
                [Op.or]: filter.vehicle.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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



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

    ];

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

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

            
            
            if (filter.calendarStart && filter.calendarEnd) {
                where = {
                    ...where,
                    [Op.or]: [
                        {
                            start_at: {
                                [Op.between]: [filter.calendarStart, filter.calendarEnd],
                            },
                    },
                {
                    end_at: {
                        [Op.between]: [filter.calendarStart, filter.calendarEnd],
                    },
                },
                ],
            };
            }
            

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

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

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

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    end_at: {
                    ...where.end_at,
                            [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.cost_amountRange) {
                const [start, end] = filter.cost_amountRange;

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

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

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

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


      

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

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

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

    
};

