
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
            ,
            
        planned_quantity: data.planned_quantity
        ||
        null
            ,
            
        completed_quantity: data.completed_quantity
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        planned_start: data.planned_start
        ||
        null
            ,
            
        planned_end: data.planned_end
        ||
        null
            ,
            
        actual_start: data.actual_start
        ||
        null
            ,
            
        actual_end: data.actual_end
        ||
        null
            ,
            
        customer_reference: data.customer_reference
        ||
        null
            ,
            
        notes: data.notes
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { 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.setPlanner( data.planner || 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
            ,
            
                planned_quantity: item.planned_quantity
            ||
            null
            ,
            
                completed_quantity: item.completed_quantity
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
                planned_start: item.planned_start
            ||
            null
            ,
            
                planned_end: item.planned_end
            ||
            null
            ,
            
                actual_start: item.actual_start
            ||
            null
            ,
            
                actual_end: item.actual_end
            ||
            null
            ,
            
                customer_reference: item.customer_reference
            ||
            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 production_orders = await db.production_orders.findByPk(id, {}, {transaction});


        

        const updatePayload = {};
        
        if (data.order_number !== undefined) updatePayload.order_number = data.order_number;
        
        
        if (data.planned_quantity !== undefined) updatePayload.planned_quantity = data.planned_quantity;
        
        
        if (data.completed_quantity !== undefined) updatePayload.completed_quantity = data.completed_quantity;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.planned_start !== undefined) updatePayload.planned_start = data.planned_start;
        
        
        if (data.planned_end !== undefined) updatePayload.planned_end = data.planned_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.customer_reference !== undefined) updatePayload.customer_reference = data.customer_reference;
        
        
        if (data.notes !== undefined) updatePayload.notes = data.notes;
        
        
        updatePayload.updatedById = currentUser.id;

        await production_orders.update(updatePayload, {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.planner !== undefined) {
            await production_orders.setPlanner(
              
              data.planner,
              
              { 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.production_material_issues_production_order = await production_orders.getProduction_material_issues_production_order({
            transaction
        });
        
        
        output.production_lots_production_order = await production_orders.getProduction_lots_production_order({
            transaction
        });
        
        
        output.qa_inspections_production_order = await production_orders.getQa_inspections_production_order({
            transaction
        });
        
        
        
        
        
        output.nonconformances_production_order = await production_orders.getNonconformances_production_order({
            transaction
        });
        
        
        
        
        
        output.material = await production_orders.getMaterial({
            transaction
        });
        
        
        output.bom = await production_orders.getBom({
            transaction
        });
        
        
        output.routing = await production_orders.getRouting({
            transaction
        });
        
        
        output.planner = await production_orders.getPlanner({
            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.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.boms,
        as: 'bom',
        
        where: filter.bom ? {
          [Op.or]: [
            { id: { [Op.in]: filter.bom.split('|').map(term => Utils.uuid(term)) } },
            {
              bom_code: {
                [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_code: {
                [Op.or]: filter.routing.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}%` }))
              }
            },
          ]
        } : {},
        
      },



    ];

        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.customer_reference) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'production_orders',
                        'customer_reference',
                        filter.customer_reference,
                    ),
                };
            }
            
            if (filter.notes) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'production_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.planned_startRange) {
                const [start, end] = filter.planned_startRange;

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

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

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

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

        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,
        }));
    }

    
};

