
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
            ,
            
        scrap_quantity: data.scrap_quantity
        ||
        null
            ,
            
        scheduled_start: data.scheduled_start
        ||
        null
            ,
            
        scheduled_end: data.scheduled_end
        ||
        null
            ,
            
        released_at: data.released_at
        ||
        null
            ,
            
        completed_at: data.completed_at
        ||
        null
            ,
            
        priority: data.priority
        ||
        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.setRouting( data.routing || null, {
            transaction,
        });
        
        await work_orders.setCustomer( data.customer || null, {
            transaction,
        });
        

        

        

        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
            ,
            
                scrap_quantity: item.scrap_quantity
            ||
            null
            ,
            
                scheduled_start: item.scheduled_start
            ||
            null
            ,
            
                scheduled_end: item.scheduled_end
            ||
            null
            ,
            
                released_at: item.released_at
            ||
            null
            ,
            
                completed_at: item.completed_at
            ||
            null
            ,
            
                priority: item.priority
            ||
            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
        

        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.scrap_quantity !== undefined) updatePayload.scrap_quantity = data.scrap_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.released_at !== undefined) updatePayload.released_at = data.released_at;
        
        
        if (data.completed_at !== undefined) updatePayload.completed_at = data.completed_at;
        
        
        if (data.priority !== undefined) updatePayload.priority = data.priority;
        
        
        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.routing !== undefined) {
            await work_orders.setRouting(
              
              data.routing,
              
              { transaction }
            );
        }
        
        if (data.customer !== undefined) {
            await work_orders.setCustomer(
              
              data.customer,
              
              { transaction }
            );
        }
        

        
        

        

        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.machine_events_work_order = await work_orders.getMachine_events_work_order({
            transaction
        });
        
        
        
        
        output.work_order_operations_work_order = await work_orders.getWork_order_operations_work_order({
            transaction
        });
        
        
        
        
        
        output.inventory_movements_work_order = await work_orders.getInventory_movements_work_order({
            transaction
        });
        
        
        
        
        
        
        output.inspections_work_order = await work_orders.getInspections_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.routing = await work_orders.getRouting({
            transaction
        });
        
        
        output.customer = await work_orders.getCustomer({
            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.routings,
        as: 'routing',
        
        where: filter.routing ? {
          [Op.or]: [
            { id: { [Op.in]: filter.routing.split('|').map(term => Utils.uuid(term)) } },
            {
              routing_name: {
                [Op.or]: filter.routing.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}%` }))
              }
            },
          ]
        } : {},
        
      },



    ];

        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.priority) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'work_orders',
                        'priority',
                        filter.priority,
                    ),
                };
            }
            
            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.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.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.released_atRange) {
                const [start, end] = filter.released_atRange;

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

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

    
};

