
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_at: data.planned_start_at
        ||
        null
            ,
            
        planned_end_at: data.planned_end_at
        ||
        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 production_orders.setItem( data.item || null, {
            transaction,
        });
        
        await production_orders.setBom( data.bom || null, {
            transaction,
        });
        
        await production_orders.setRouting( data.routing || null, {
            transaction,
        });
        
        await production_orders.setWarehouse( data.warehouse || null, {
            transaction,
        });
        
        await production_orders.setCreated_by_user( data.created_by_user || 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_at: item.planned_start_at
            ||
            null
            ,
            
                planned_end_at: item.planned_end_at
            ||
            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 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_at !== undefined) updatePayload.planned_start_at = data.planned_start_at;
        
        
        if (data.planned_end_at !== undefined) updatePayload.planned_end_at = data.planned_end_at;
        
        
        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 production_orders.update(updatePayload, {transaction});

        
        
        if (data.item !== undefined) {
            await production_orders.setItem(
              
              data.item,
              
              { 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.warehouse !== undefined) {
            await production_orders.setWarehouse(
              
              data.warehouse,
              
              { transaction }
            );
        }
        
        if (data.created_by_user !== undefined) {
            await production_orders.setCreated_by_user(
              
              data.created_by_user,
              
              { 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_issues_production_order = await production_orders.getMaterial_issues_production_order({
            transaction
        });
        
        
        output.production_receipts_production_order = await production_orders.getProduction_receipts_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.production_costs_production_order = await production_orders.getProduction_costs_production_order({
            transaction
        });
        
        
        
        
        
        
        output.item = await production_orders.getItem({
            transaction
        });
        
        
        output.bom = await production_orders.getBom({
            transaction
        });
        
        
        output.routing = await production_orders.getRouting({
            transaction
        });
        
        
        output.warehouse = await production_orders.getWarehouse({
            transaction
        });
        
        
        output.created_by_user = await production_orders.getCreated_by_user({
            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)) } },
            {
              name: {
                [Op.or]: filter.item.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)) } },
            {
              bom_code: {
                [Op.or]: filter.bom.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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



    ];

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

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

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

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

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

    
};

