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

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

        const production_orders = await db.production_orders.create(
            {
                id: data.id || undefined,
        
        order_number: data.order_number
        ||
        null
            ,
            
        status: data.status
        ||
        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
            ,
            
        planned_qty: data.planned_qty
        ||
        null
            ,
            
        completed_qty: data.completed_qty
        ||
        null
            ,
            
        scrapped_qty: data.scrapped_qty
        ||
        null
            ,
            
        uom: data.uom
        ||
        null
            ,
            
        priority: data.priority
        ||
        null
            ,
            
        notes: data.notes
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await production_orders.setPlant( data.plant || null, {
            transaction,
        });
        
        await production_orders.setMaterial( data.material || null, {
            transaction,
        });
        
        await production_orders.setBom( data.bom || null, {
            transaction,
        });
        
        await production_orders.setRouting( data.routing || null, {
            transaction,
        });
        
        await production_orders.setCustomer( data.customer || null, {
            transaction,
        });
        
        await production_orders.setCreated_by_user( data.created_by_user || null, {
            transaction,
        });
        
        await production_orders.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

        

        return production_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 production_ordersData = data.map((item, index) => ({
                id: item.id || undefined,
                
                order_number: item.order_number
            ||
            null
            ,
            
                status: item.status
            ||
            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
            ,
            
                planned_qty: item.planned_qty
            ||
            null
            ,
            
                completed_qty: item.completed_qty
            ||
            null
            ,
            
                scrapped_qty: item.scrapped_qty
            ||
            null
            ,
            
                uom: item.uom
            ||
            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 production_orders = await db.production_orders.bulkCreate(production_ordersData, { transaction });

        // For each item created, replace relation files
        

        return production_orders;
    }

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


        

        const updatePayload = {};
        
        if (data.order_number !== undefined) updatePayload.order_number = data.order_number;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        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.planned_qty !== undefined) updatePayload.planned_qty = data.planned_qty;
        
        
        if (data.completed_qty !== undefined) updatePayload.completed_qty = data.completed_qty;
        
        
        if (data.scrapped_qty !== undefined) updatePayload.scrapped_qty = data.scrapped_qty;
        
        
        if (data.uom !== undefined) updatePayload.uom = data.uom;
        
        
        if (data.priority !== undefined) updatePayload.priority = data.priority;
        
        
        if (data.notes !== undefined) updatePayload.notes = data.notes;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.plant !== undefined) {
            await production_orders.setPlant(
              
              data.plant,
              
              { transaction }
            );
        }
        
        if (data.material !== undefined) {
            await production_orders.setMaterial(
              
              data.material,
              
              { transaction }
            );
        }
        
        if (data.bom !== undefined) {
            await production_orders.setBom(
              
              data.bom,
              
              { transaction }
            );
        }
        
        if (data.routing !== undefined) {
            await production_orders.setRouting(
              
              data.routing,
              
              { transaction }
            );
        }
        
        if (data.customer !== undefined) {
            await production_orders.setCustomer(
              
              data.customer,
              
              { transaction }
            );
        }
        
        if (data.created_by_user !== undefined) {
            await production_orders.setCreated_by_user(
              
              data.created_by_user,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await production_orders.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        

        

        return production_orders;
    }

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

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

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


        return production_orders;
    }

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

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

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

        await production_orders.destroy({
            transaction
        });

        return production_orders;
    }

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

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

        if (!production_orders) {
            return production_orders;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.production_operations_production_order = await production_orders.getProduction_operations_production_order({
            transaction
        });
        
        
        output.material_allocations_production_order = await production_orders.getMaterial_allocations_production_order({
            transaction
        });
        
        
        output.production_lots_production_order = await production_orders.getProduction_lots_production_order({
            transaction
        });
        
        
        
        
        output.inspections_production_order = await production_orders.getInspections_production_order({
            transaction
        });
        
        
        
        output.nonconformances_production_order = await production_orders.getNonconformances_production_order({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        output.plant = await production_orders.getPlant({
            transaction
        });
        
        
        output.material = await production_orders.getMaterial({
            transaction
        });
        
        
        output.bom = await production_orders.getBom({
            transaction
        });
        
        
        output.routing = await production_orders.getRouting({
            transaction
        });
        
        
        output.customer = await production_orders.getCustomer({
            transaction
        });
        
        
        output.created_by_user = await production_orders.getCreated_by_user({
            transaction
        });
        
        
        output.organizations = await production_orders.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.plants,
        as: 'plant',
        
        where: filter.plant ? {
          [Op.or]: [
            { id: { [Op.in]: filter.plant.split('|').map(term => Utils.uuid(term)) } },
            {
              name: {
                [Op.or]: filter.plant.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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

      {
        model: db.bom_headers,
        as: 'bom',
        
        where: filter.bom ? {
          [Op.or]: [
            { id: { [Op.in]: filter.bom.split('|').map(term => Utils.uuid(term)) } },
            {
              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)) } },
            {
              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)) } },
            {
              name: {
                [Op.or]: filter.customer.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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

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



    ];

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

            
            if (filter.order_number) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'production_orders',
                        'order_number',
                        filter.order_number,
                    ),
                };
            }
            
            if (filter.uom) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'production_orders',
                        'uom',
                        filter.uom,
                    ),
                };
            }
            
            if (filter.priority) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'production_orders',
                        'priority',
                        filter.priority,
                    ),
                };
            }
            
            if (filter.notes) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'production_orders',
                        'notes',
                        filter.notes,
                    ),
                };
            }
            

            
            

            
            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.planned_qtyRange) {
                const [start, end] = filter.planned_qtyRange;

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

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

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

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

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

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

        if (query) {
            where = {
                [Op.or]: [
                    { ['id']: Utils.uuid(query) },
                    Utils.ilike(
                        'production_orders',
                        'order_number',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

