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

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

        const work_orders = await db.work_orders.create(
            {
                id: data.id || undefined,
        
        work_order_number: data.work_order_number
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        planned_quantity: data.planned_quantity
        ||
        null
            ,
            
        completed_quantity: data.completed_quantity
        ||
        null
            ,
            
        scheduled_start: data.scheduled_start
        ||
        null
            ,
            
        scheduled_end: data.scheduled_end
        ||
        null
            ,
            
        actual_start: data.actual_start
        ||
        null
            ,
            
        actual_end: data.actual_end
        ||
        null
            ,
            
        notes: data.notes
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await work_orders.setItem( data.item || null, {
            transaction,
        });
        
        await work_orders.setBom( data.bom || null, {
            transaction,
        });
        
        await work_orders.setRoute( data.route || null, {
            transaction,
        });
        
        await work_orders.setCustomer( data.customer || null, {
            transaction,
        });
        
        await work_orders.setUom( data.uom || null, {
            transaction,
        });
        
        await work_orders.setProduction_line( data.production_line || null, {
            transaction,
        });
        
        await work_orders.setPrimary_machine( data.primary_machine || null, {
            transaction,
        });
        
        await work_orders.setPlanner( data.planner || null, {
            transaction,
        });
        

        

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

        return 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 work_ordersData = data.map((item, index) => ({
                id: item.id || undefined,
                
                work_order_number: item.work_order_number
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
                planned_quantity: item.planned_quantity
            ||
            null
            ,
            
                completed_quantity: item.completed_quantity
            ||
            null
            ,
            
                scheduled_start: item.scheduled_start
            ||
            null
            ,
            
                scheduled_end: item.scheduled_end
            ||
            null
            ,
            
                actual_start: item.actual_start
            ||
            null
            ,
            
                actual_end: item.actual_end
            ||
            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 work_orders = await db.work_orders.bulkCreate(work_ordersData, { transaction });

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

        return work_orders;
    }

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

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


        

        const updatePayload = {};
        
        if (data.work_order_number !== undefined) updatePayload.work_order_number = data.work_order_number;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.planned_quantity !== undefined) updatePayload.planned_quantity = data.planned_quantity;
        
        
        if (data.completed_quantity !== undefined) updatePayload.completed_quantity = data.completed_quantity;
        
        
        if (data.scheduled_start !== undefined) updatePayload.scheduled_start = data.scheduled_start;
        
        
        if (data.scheduled_end !== undefined) updatePayload.scheduled_end = data.scheduled_end;
        
        
        if (data.actual_start !== undefined) updatePayload.actual_start = data.actual_start;
        
        
        if (data.actual_end !== undefined) updatePayload.actual_end = data.actual_end;
        
        
        if (data.notes !== undefined) updatePayload.notes = data.notes;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.item !== undefined) {
            await work_orders.setItem(
              
              data.item,
              
              { transaction }
            );
        }
        
        if (data.bom !== undefined) {
            await work_orders.setBom(
              
              data.bom,
              
              { transaction }
            );
        }
        
        if (data.route !== undefined) {
            await work_orders.setRoute(
              
              data.route,
              
              { transaction }
            );
        }
        
        if (data.customer !== undefined) {
            await work_orders.setCustomer(
              
              data.customer,
              
              { transaction }
            );
        }
        
        if (data.uom !== undefined) {
            await work_orders.setUom(
              
              data.uom,
              
              { transaction }
            );
        }
        
        if (data.production_line !== undefined) {
            await work_orders.setProduction_line(
              
              data.production_line,
              
              { transaction }
            );
        }
        
        if (data.primary_machine !== undefined) {
            await work_orders.setPrimary_machine(
              
              data.primary_machine,
              
              { transaction }
            );
        }
        
        if (data.planner !== undefined) {
            await work_orders.setPlanner(
              
              data.planner,
              
              { transaction }
            );
        }
        

        
        

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

        return work_orders;
    }

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

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

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


        return work_orders;
    }

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

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

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

        await work_orders.destroy({
            transaction
        });

        return work_orders;
    }

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

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

        if (!work_orders) {
            return work_orders;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        output.inventory_transactions_work_order = await work_orders.getInventory_transactions_work_order({
            transaction
        });
        
        
        
        
        
        
        
        output.machine_downtime_events_work_order = await work_orders.getMachine_downtime_events_work_order({
            transaction
        });
        
        
        
        
        
        output.work_order_operations_work_order = await work_orders.getWork_order_operations_work_order({
            transaction
        });
        
        
        output.material_issues_work_order = await work_orders.getMaterial_issues_work_order({
            transaction
        });
        
        
        
        
        
        
        
        
        
        output.qa_inspections_work_order = await work_orders.getQa_inspections_work_order({
            transaction
        });
        
        
        
        output.nonconformances_work_order = await work_orders.getNonconformances_work_order({
            transaction
        });
        
        
        
        
        output.item = await work_orders.getItem({
            transaction
        });
        
        
        output.bom = await work_orders.getBom({
            transaction
        });
        
        
        output.route = await work_orders.getRoute({
            transaction
        });
        
        
        output.customer = await work_orders.getCustomer({
            transaction
        });
        
        
        output.uom = await work_orders.getUom({
            transaction
        });
        
        
        output.production_line = await work_orders.getProduction_line({
            transaction
        });
        
        
        output.primary_machine = await work_orders.getPrimary_machine({
            transaction
        });
        
        
        output.planner = await work_orders.getPlanner({
            transaction
        });
        
        
        output.attachments = await 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.items,
        as: 'item',
        
        where: filter.item ? {
          [Op.or]: [
            { id: { [Op.in]: filter.item.split('|').map(term => Utils.uuid(term)) } },
            {
              item_name: {
                [Op.or]: filter.item.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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

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

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

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

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

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

      {
        model: db.users,
        as: 'planner',
        
        where: filter.planner ? {
          [Op.or]: [
            { id: { [Op.in]: filter.planner.split('|').map(term => Utils.uuid(term)) } },
            {
              firstName: {
                [Op.or]: filter.planner.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(
                        'work_orders',
                        'work_order_number',
                        filter.work_order_number,
                    ),
                };
            }
            
            if (filter.notes) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'work_orders',
                        'notes',
                        filter.notes,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

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

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    actual_end: {
                    ...where.actual_end,
                            [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.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.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(
                        'work_orders',
                        'work_order_number',
                        query,
                    ),
                ],
            };
        }

        const records = await db.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,
        }));
    }

    
};

