
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_sequence: data.operation_sequence
        ||
        null
            ,
            
        name: data.name
        ||
        null
            ,
            
        status: data.status
        ||
        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
            ,
            
        labor_minutes: data.labor_minutes
        ||
        null
            ,
            
        machine_minutes: data.machine_minutes
        ||
        null
            ,
            
        instructions: data.instructions
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await production_operations.setWork_order( data.work_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_sequence: item.operation_sequence
            ||
            null
            ,
            
                name: item.name
            ||
            null
            ,
            
                status: item.status
            ||
            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
            ,
            
                labor_minutes: item.labor_minutes
            ||
            null
            ,
            
                machine_minutes: item.machine_minutes
            ||
            null
            ,
            
                instructions: item.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_sequence !== undefined) updatePayload.operation_sequence = data.operation_sequence;
        
        
        if (data.name !== undefined) updatePayload.name = data.name;
        
        
        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.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.labor_minutes !== undefined) updatePayload.labor_minutes = data.labor_minutes;
        
        
        if (data.machine_minutes !== undefined) updatePayload.machine_minutes = data.machine_minutes;
        
        
        if (data.instructions !== undefined) updatePayload.instructions = data.instructions;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.work_order !== undefined) {
            await production_operations.setWork_order(
              
              data.work_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.work_order = await production_operations.getWork_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.work_orders,
        as: 'work_order',
        
        where: filter.work_order ? {
          [Op.or]: [
            { id: { [Op.in]: filter.work_order.split('|').map(term => Utils.uuid(term)) } },
            {
              work_order_number: {
                [Op.or]: filter.work_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.name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'production_operations',
                        'name',
                        filter.name,
                    ),
                };
            }
            
            if (filter.instructions) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'production_operations',
                        'instructions',
                        filter.instructions,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

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

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

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

    
};

