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

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

        const production_operations = await db.production_operations.create(
            {
                id: data.id || undefined,
        
        status: data.status
        ||
        null
            ,
            
        scheduled_start_at: data.scheduled_start_at
        ||
        null
            ,
            
        scheduled_end_at: data.scheduled_end_at
        ||
        null
            ,
            
        actual_start_at: data.actual_start_at
        ||
        null
            ,
            
        actual_end_at: data.actual_end_at
        ||
        null
            ,
            
        good_quantity: data.good_quantity
        ||
        null
            ,
            
        scrap_quantity: data.scrap_quantity
        ||
        null
            ,
            
        operator_notes: data.operator_notes
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await production_operations.setProduction_order( data.production_order || null, {
            transaction,
        });
        
        await production_operations.setRouting_operation( data.routing_operation || null, {
            transaction,
        });
        
        await production_operations.setMachine( data.machine || null, {
            transaction,
        });
        

        

        

        return production_operations;
    }
    

    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_operationsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                status: item.status
            ||
            null
            ,
            
                scheduled_start_at: item.scheduled_start_at
            ||
            null
            ,
            
                scheduled_end_at: item.scheduled_end_at
            ||
            null
            ,
            
                actual_start_at: item.actual_start_at
            ||
            null
            ,
            
                actual_end_at: item.actual_end_at
            ||
            null
            ,
            
                good_quantity: item.good_quantity
            ||
            null
            ,
            
                scrap_quantity: item.scrap_quantity
            ||
            null
            ,
            
                operator_notes: item.operator_notes
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

        // Bulk create items
        const production_operations = await db.production_operations.bulkCreate(production_operationsData, { transaction });

        // For each item created, replace relation files
        

        return production_operations;
    }

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

        const production_operations = await db.production_operations.findByPk(id, {}, {transaction});


        

        const updatePayload = {};
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.scheduled_start_at !== undefined) updatePayload.scheduled_start_at = data.scheduled_start_at;
        
        
        if (data.scheduled_end_at !== undefined) updatePayload.scheduled_end_at = data.scheduled_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.good_quantity !== undefined) updatePayload.good_quantity = data.good_quantity;
        
        
        if (data.scrap_quantity !== undefined) updatePayload.scrap_quantity = data.scrap_quantity;
        
        
        if (data.operator_notes !== undefined) updatePayload.operator_notes = data.operator_notes;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.production_order !== undefined) {
            await production_operations.setProduction_order(
              
              data.production_order,
              
              { transaction }
            );
        }
        
        if (data.routing_operation !== undefined) {
            await production_operations.setRouting_operation(
              
              data.routing_operation,
              
              { transaction }
            );
        }
        
        if (data.machine !== undefined) {
            await production_operations.setMachine(
              
              data.machine,
              
              { transaction }
            );
        }
        

        
        

        

        return production_operations;
    }

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

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

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


        return production_operations;
    }

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

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

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

        await production_operations.destroy({
            transaction
        });

        return production_operations;
    }

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

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

        if (!production_operations) {
            return production_operations;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.production_order = await production_operations.getProduction_order({
            transaction
        });
        
        
        output.routing_operation = await production_operations.getRouting_operation({
            transaction
        });
        
        
        output.machine = await production_operations.getMachine({
            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.production_orders,
        as: 'production_order',
        
        where: filter.production_order ? {
          [Op.or]: [
            { id: { [Op.in]: filter.production_order.split('|').map(term => Utils.uuid(term)) } },
            {
              order_number: {
                [Op.or]: filter.production_order.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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

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



    ];

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

            
            if (filter.operator_notes) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'production_operations',
                        'operator_notes',
                        filter.operator_notes,
                    ),
                };
            }
            

            
            
            if (filter.calendarStart && filter.calendarEnd) {
                where = {
                    ...where,
                    [Op.or]: [
                        {
                            scheduled_start_at: {
                                [Op.between]: [filter.calendarStart, filter.calendarEnd],
                            },
                    },
                {
                    scheduled_end_at: {
                        [Op.between]: [filter.calendarStart, filter.calendarEnd],
                    },
                },
                ],
            };
            }
            

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

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

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

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

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

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

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

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    scrap_quantity: {
                    ...where.scrap_quantity,
                            [Op.lte]: end,
                    },
                };
                }
            }
            

            if (filter.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_operations.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_operations',
                        'operator_notes',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

