
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,
        
        operation_name: data.operation_name
        ||
        null
            ,
            
        sequence: data.sequence
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        planned_run_hours: data.planned_run_hours
        ||
        null
            ,
            
        actual_run_hours: data.actual_run_hours
        ||
        null
            ,
            
        start_at: data.start_at
        ||
        null
            ,
            
        end_at: data.end_at
        ||
        null
            ,
            
        work_instructions: data.work_instructions
        ||
        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.setMachine( data.machine || null, {
            transaction,
        });
        
        await production_operations.setOrganizations( data.organizations || 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,
                
                operation_name: item.operation_name
            ||
            null
            ,
            
                sequence: item.sequence
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
                planned_run_hours: item.planned_run_hours
            ||
            null
            ,
            
                actual_run_hours: item.actual_run_hours
            ||
            null
            ,
            
                start_at: item.start_at
            ||
            null
            ,
            
                end_at: item.end_at
            ||
            null
            ,
            
                work_instructions: item.work_instructions
            ||
            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 globalAccess = currentUser.app_role?.globalAccess;

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


        

        const updatePayload = {};
        
        if (data.operation_name !== undefined) updatePayload.operation_name = data.operation_name;
        
        
        if (data.sequence !== undefined) updatePayload.sequence = data.sequence;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.planned_run_hours !== undefined) updatePayload.planned_run_hours = data.planned_run_hours;
        
        
        if (data.actual_run_hours !== undefined) updatePayload.actual_run_hours = data.actual_run_hours;
        
        
        if (data.start_at !== undefined) updatePayload.start_at = data.start_at;
        
        
        if (data.end_at !== undefined) updatePayload.end_at = data.end_at;
        
        
        if (data.work_instructions !== undefined) updatePayload.work_instructions = data.work_instructions;
        
        
        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.machine !== undefined) {
            await production_operations.setMachine(
              
              data.machine,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await production_operations.setOrganizations(
              
              data.organizations,
              
              { 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.machine = await production_operations.getMachine({
            transaction
        });
        
        
        output.organizations = await production_operations.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.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.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}%` }))
              }
            },
          ]
        } : {},
        
      },

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



    ];

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

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

            
            

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
};

