
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
            ,
            
        priority: data.priority
        ||
        null
            ,
            
        quantity_planned: data.quantity_planned
        ||
        null
            ,
            
        quantity_completed: data.quantity_completed
        ||
        null
            ,
            
        planned_start_at: data.planned_start_at
        ||
        null
            ,
            
        planned_end_at: data.planned_end_at
        ||
        null
            ,
            
        actual_start_at: data.actual_start_at
        ||
        null
            ,
            
        actual_end_at: data.actual_end_at
        ||
        null
            ,
            
        customer_order_ref: data.customer_order_ref
        ||
        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.setItem( data.item || 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,
        });
        

        

        

        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
            ,
            
                priority: item.priority
            ||
            null
            ,
            
                quantity_planned: item.quantity_planned
            ||
            null
            ,
            
                quantity_completed: item.quantity_completed
            ||
            null
            ,
            
                planned_start_at: item.planned_start_at
            ||
            null
            ,
            
                planned_end_at: item.planned_end_at
            ||
            null
            ,
            
                actual_start_at: item.actual_start_at
            ||
            null
            ,
            
                actual_end_at: item.actual_end_at
            ||
            null
            ,
            
                customer_order_ref: item.customer_order_ref
            ||
            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.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.priority !== undefined) updatePayload.priority = data.priority;
        
        
        if (data.quantity_planned !== undefined) updatePayload.quantity_planned = data.quantity_planned;
        
        
        if (data.quantity_completed !== undefined) updatePayload.quantity_completed = data.quantity_completed;
        
        
        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.actual_start_at !== undefined) updatePayload.actual_start_at = data.actual_start_at;
        
        
        if (data.actual_end_at !== undefined) updatePayload.actual_end_at = data.actual_end_at;
        
        
        if (data.customer_order_ref !== undefined) updatePayload.customer_order_ref = data.customer_order_ref;
        
        
        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.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.customer !== undefined) {
            await production_orders.setCustomer(
              
              data.customer,
              
              { 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.downtime_events_production_order = await production_orders.getDowntime_events_production_order({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.production_operations_production_order = await production_orders.getProduction_operations_production_order({
            transaction
        });
        
        
        output.production_materials_production_order = await production_orders.getProduction_materials_production_order({
            transaction
        });
        
        
        output.production_outputs_production_order = await production_orders.getProduction_outputs_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.journal_lines_production_order = await production_orders.getJournal_lines_production_order({
            transaction
        });
        
        
        
        
        
        output.plant = await production_orders.getPlant({
            transaction
        });
        
        
        output.item = await production_orders.getItem({
            transaction
        });
        
        
        output.bom = await production_orders.getBom({
            transaction
        });
        
        
        output.routing = await production_orders.getRouting({
            transaction
        });
        
        
        output.customer = await production_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.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.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.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.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}%` }))
              }
            },
          ]
        } : {},
        
      },



    ];

        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_order_ref) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'production_orders',
                        'customer_order_ref',
                        filter.customer_order_ref,
                    ),
                };
            }
            
            if (filter.notes) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'production_orders',
                        'notes',
                        filter.notes,
                    ),
                };
            }
            

            
            

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

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

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

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    quantity_completed: {
                    ...where.quantity_completed,
                            [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.actual_start_atRange) {
                const [start, end] = filter.actual_start_atRange;

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

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

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

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


      

      

      

      

      



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

    
};

