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

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

        const maintenance_work_orders = await db.maintenance_work_orders.create(
            {
                id: data.id || undefined,
        
        work_order_number: data.work_order_number
        ||
        null
            ,
            
        work_type: data.work_type
        ||
        null
            ,
            
        priority: data.priority
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        requested_at: data.requested_at
        ||
        null
            ,
            
        scheduled_start: data.scheduled_start
        ||
        null
            ,
            
        scheduled_end: data.scheduled_end
        ||
        null
            ,
            
        completed_at: data.completed_at
        ||
        null
            ,
            
        problem_description: data.problem_description
        ||
        null
            ,
            
        resolution_summary: data.resolution_summary
        ||
        null
            ,
            
        labor_hours: data.labor_hours
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await maintenance_work_orders.setMachine( data.machine || null, {
            transaction,
        });
        
        await maintenance_work_orders.setRequested_by( data.requested_by || null, {
            transaction,
        });
        
        await maintenance_work_orders.setAssigned_to( data.assigned_to || null, {
            transaction,
        });
        

        

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

        return maintenance_work_orders;
    }
    

    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_work_ordersData = data.map((item, index) => ({
                id: item.id || undefined,
                
                work_order_number: item.work_order_number
            ||
            null
            ,
            
                work_type: item.work_type
            ||
            null
            ,
            
                priority: item.priority
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
                requested_at: item.requested_at
            ||
            null
            ,
            
                scheduled_start: item.scheduled_start
            ||
            null
            ,
            
                scheduled_end: item.scheduled_end
            ||
            null
            ,
            
                completed_at: item.completed_at
            ||
            null
            ,
            
                problem_description: item.problem_description
            ||
            null
            ,
            
                resolution_summary: item.resolution_summary
            ||
            null
            ,
            
                labor_hours: item.labor_hours
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

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

        return maintenance_work_orders;
    }

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

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


        

        const updatePayload = {};
        
        if (data.work_order_number !== undefined) updatePayload.work_order_number = data.work_order_number;
        
        
        if (data.work_type !== undefined) updatePayload.work_type = data.work_type;
        
        
        if (data.priority !== undefined) updatePayload.priority = data.priority;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.requested_at !== undefined) updatePayload.requested_at = data.requested_at;
        
        
        if (data.scheduled_start !== undefined) updatePayload.scheduled_start = data.scheduled_start;
        
        
        if (data.scheduled_end !== undefined) updatePayload.scheduled_end = data.scheduled_end;
        
        
        if (data.completed_at !== undefined) updatePayload.completed_at = data.completed_at;
        
        
        if (data.problem_description !== undefined) updatePayload.problem_description = data.problem_description;
        
        
        if (data.resolution_summary !== undefined) updatePayload.resolution_summary = data.resolution_summary;
        
        
        if (data.labor_hours !== undefined) updatePayload.labor_hours = data.labor_hours;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.machine !== undefined) {
            await maintenance_work_orders.setMachine(
              
              data.machine,
              
              { transaction }
            );
        }
        
        if (data.requested_by !== undefined) {
            await maintenance_work_orders.setRequested_by(
              
              data.requested_by,
              
              { transaction }
            );
        }
        
        if (data.assigned_to !== undefined) {
            await maintenance_work_orders.setAssigned_to(
              
              data.assigned_to,
              
              { transaction }
            );
        }
        

        
        

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

        return maintenance_work_orders;
    }

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

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

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


        return maintenance_work_orders;
    }

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

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

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

        await maintenance_work_orders.destroy({
            transaction
        });

        return maintenance_work_orders;
    }

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

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

        if (!maintenance_work_orders) {
            return maintenance_work_orders;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.machine = await maintenance_work_orders.getMachine({
            transaction
        });
        
        
        output.requested_by = await maintenance_work_orders.getRequested_by({
            transaction
        });
        
        
        output.assigned_to = await maintenance_work_orders.getAssigned_to({
            transaction
        });
        
        
        output.attachments = await maintenance_work_orders.getAttachments({
            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.machines,
        as: 'machine',
        
        where: filter.machine ? {
          [Op.or]: [
            { id: { [Op.in]: filter.machine.split('|').map(term => Utils.uuid(term)) } },
            {
              name: {
                [Op.or]: filter.machine.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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

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



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

    ];

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

            
            if (filter.work_order_number) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'maintenance_work_orders',
                        'work_order_number',
                        filter.work_order_number,
                    ),
                };
            }
            
            if (filter.problem_description) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'maintenance_work_orders',
                        'problem_description',
                        filter.problem_description,
                    ),
                };
            }
            
            if (filter.resolution_summary) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'maintenance_work_orders',
                        'resolution_summary',
                        filter.resolution_summary,
                    ),
                };
            }
            

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

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

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

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

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

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

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

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

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

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

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

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

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

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


      

      

      



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

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

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

    
};

