
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,
        
        name: data.name
        ||
        null
            ,
            
        sequence: data.sequence
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        scheduled_start_at: data.scheduled_start_at
        ||
        null
            ,
            
        scheduled_end_at: data.scheduled_end_at
        ||
        null
            ,
            
        started_at: data.started_at
        ||
        null
            ,
            
        ended_at: data.ended_at
        ||
        null
            ,
            
        planned_quantity: data.planned_quantity
        ||
        null
            ,
            
        good_quantity: data.good_quantity
        ||
        null
            ,
            
        scrap_quantity: data.scrap_quantity
        ||
        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.setAssigned_to( data.assigned_to || null, {
            transaction,
        });
        
        await production_operations.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

        
        await FileDBApi.replaceRelationFiles(
            {
                belongsTo: db.production_operations.getTableName(),
                belongsToColumn: 'attachments',
                belongsToId: production_operations.id,
            },
            data.attachments,
            options,
        );
        

        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,
                
                name: item.name
            ||
            null
            ,
            
                sequence: item.sequence
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
                scheduled_start_at: item.scheduled_start_at
            ||
            null
            ,
            
                scheduled_end_at: item.scheduled_end_at
            ||
            null
            ,
            
                started_at: item.started_at
            ||
            null
            ,
            
                ended_at: item.ended_at
            ||
            null
            ,
            
                planned_quantity: item.planned_quantity
            ||
            null
            ,
            
                good_quantity: item.good_quantity
            ||
            null
            ,
            
                scrap_quantity: item.scrap_quantity
            ||
            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
        
        for (let i = 0; i < production_operations.length; i++) {
            await FileDBApi.replaceRelationFiles(
                {
                    belongsTo: db.production_operations.getTableName(),
                    belongsToColumn: 'attachments',
                    belongsToId: production_operations[i].id,
                },
                data[i].attachments,
                options,
            );
        }
        

        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.name !== undefined) updatePayload.name = data.name;
        
        
        if (data.sequence !== undefined) updatePayload.sequence = data.sequence;
        
        
        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.started_at !== undefined) updatePayload.started_at = data.started_at;
        
        
        if (data.ended_at !== undefined) updatePayload.ended_at = data.ended_at;
        
        
        if (data.planned_quantity !== undefined) updatePayload.planned_quantity = data.planned_quantity;
        
        
        if (data.good_quantity !== undefined) updatePayload.good_quantity = data.good_quantity;
        
        
        if (data.scrap_quantity !== undefined) updatePayload.scrap_quantity = data.scrap_quantity;
        
        
        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.assigned_to !== undefined) {
            await production_operations.setAssigned_to(
              
              data.assigned_to,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await production_operations.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        

        
        await FileDBApi.replaceRelationFiles(
            {
                belongsTo: db.production_operations.getTableName(),
                belongsToColumn: 'attachments',
                belongsToId: production_operations.id,
            },
            data.attachments,
            options,
        );
        

        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.quality_inspections_operation = await production_operations.getQuality_inspections_operation({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        output.production_order = await production_operations.getProduction_order({
            transaction
        });
        
        
        output.machine = await production_operations.getMachine({
            transaction
        });
        
        
        output.assigned_to = await production_operations.getAssigned_to({
            transaction
        });
        
        
        output.attachments = await production_operations.getAttachments({
            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.users,
        as: 'assigned_to',
        
        where: filter.assigned_to ? {
          [Op.or]: [
            { id: { [Op.in]: filter.assigned_to.split('|').map(term => Utils.uuid(term)) } },
            {
              firstName: {
                [Op.or]: filter.assigned_to.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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



      {
        model: db.file,
        as: 'attachments',
      },

    ];

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

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

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

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

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

    
};

