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

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

        const work_order_operations = await db.work_order_operations.create(
            {
                id: data.id || undefined,
        
        operation_no: data.operation_no
        ||
        null
            ,
            
        operation_name: data.operation_name
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        started_at: data.started_at
        ||
        null
            ,
            
        ended_at: data.ended_at
        ||
        null
            ,
            
        good_quantity: data.good_quantity
        ||
        null
            ,
            
        scrap_quantity: data.scrap_quantity
        ||
        null
            ,
            
        notes: data.notes
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await work_order_operations.setWork_order( data.work_order || null, {
            transaction,
        });
        
        await work_order_operations.setWork_center( data.work_center || null, {
            transaction,
        });
        
        await work_order_operations.setMachine( data.machine || null, {
            transaction,
        });
        
        await work_order_operations.setPerformed_by( data.performed_by || null, {
            transaction,
        });
        

        

        

        return work_order_operations;
    }
    

    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_order_operationsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                operation_no: item.operation_no
            ||
            null
            ,
            
                operation_name: item.operation_name
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
                started_at: item.started_at
            ||
            null
            ,
            
                ended_at: item.ended_at
            ||
            null
            ,
            
                good_quantity: item.good_quantity
            ||
            null
            ,
            
                scrap_quantity: item.scrap_quantity
            ||
            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_order_operations = await db.work_order_operations.bulkCreate(work_order_operationsData, { transaction });

        // For each item created, replace relation files
        

        return work_order_operations;
    }

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

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


        

        const updatePayload = {};
        
        if (data.operation_no !== undefined) updatePayload.operation_no = data.operation_no;
        
        
        if (data.operation_name !== undefined) updatePayload.operation_name = data.operation_name;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.started_at !== undefined) updatePayload.started_at = data.started_at;
        
        
        if (data.ended_at !== undefined) updatePayload.ended_at = data.ended_at;
        
        
        if (data.good_quantity !== undefined) updatePayload.good_quantity = data.good_quantity;
        
        
        if (data.scrap_quantity !== undefined) updatePayload.scrap_quantity = data.scrap_quantity;
        
        
        if (data.notes !== undefined) updatePayload.notes = data.notes;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.work_order !== undefined) {
            await work_order_operations.setWork_order(
              
              data.work_order,
              
              { transaction }
            );
        }
        
        if (data.work_center !== undefined) {
            await work_order_operations.setWork_center(
              
              data.work_center,
              
              { transaction }
            );
        }
        
        if (data.machine !== undefined) {
            await work_order_operations.setMachine(
              
              data.machine,
              
              { transaction }
            );
        }
        
        if (data.performed_by !== undefined) {
            await work_order_operations.setPerformed_by(
              
              data.performed_by,
              
              { transaction }
            );
        }
        

        
        

        

        return work_order_operations;
    }

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

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

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


        return work_order_operations;
    }

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

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

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

        await work_order_operations.destroy({
            transaction
        });

        return work_order_operations;
    }

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

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

        if (!work_order_operations) {
            return work_order_operations;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.work_order = await work_order_operations.getWork_order({
            transaction
        });
        
        
        output.work_center = await work_order_operations.getWork_center({
            transaction
        });
        
        
        output.machine = await work_order_operations.getMachine({
            transaction
        });
        
        
        output.performed_by = await work_order_operations.getPerformed_by({
            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.work_orders,
        as: 'work_order',
        
        where: filter.work_order ? {
          [Op.or]: [
            { id: { [Op.in]: filter.work_order.split('|').map(term => Utils.uuid(term)) } },
            {
              work_order_number: {
                [Op.or]: filter.work_order.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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

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

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



    ];

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

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

            
            

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

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

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

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

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

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

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

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

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

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

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

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

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

    
};

