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

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

        const material_requirements = await db.material_requirements.create(
            {
                id: data.id || undefined,
        
        required_quantity: data.required_quantity
        ||
        null
            ,
            
        issued_quantity: data.issued_quantity
        ||
        null
            ,
            
        issue_method: data.issue_method
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        notes: data.notes
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await material_requirements.setProduction_order( data.production_order || null, {
            transaction,
        });
        
        await material_requirements.setItem( data.item || null, {
            transaction,
        });
        
        await material_requirements.setUom( data.uom || null, {
            transaction,
        });
        

        

        

        return material_requirements;
    }
    

    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 material_requirementsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                required_quantity: item.required_quantity
            ||
            null
            ,
            
                issued_quantity: item.issued_quantity
            ||
            null
            ,
            
                issue_method: item.issue_method
            ||
            null
            ,
            
                status: item.status
            ||
            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 material_requirements = await db.material_requirements.bulkCreate(material_requirementsData, { transaction });

        // For each item created, replace relation files
        

        return material_requirements;
    }

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

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


        

        const updatePayload = {};
        
        if (data.required_quantity !== undefined) updatePayload.required_quantity = data.required_quantity;
        
        
        if (data.issued_quantity !== undefined) updatePayload.issued_quantity = data.issued_quantity;
        
        
        if (data.issue_method !== undefined) updatePayload.issue_method = data.issue_method;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.notes !== undefined) updatePayload.notes = data.notes;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.production_order !== undefined) {
            await material_requirements.setProduction_order(
              
              data.production_order,
              
              { transaction }
            );
        }
        
        if (data.item !== undefined) {
            await material_requirements.setItem(
              
              data.item,
              
              { transaction }
            );
        }
        
        if (data.uom !== undefined) {
            await material_requirements.setUom(
              
              data.uom,
              
              { transaction }
            );
        }
        

        
        

        

        return material_requirements;
    }

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

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

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


        return material_requirements;
    }

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

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

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

        await material_requirements.destroy({
            transaction
        });

        return material_requirements;
    }

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

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

        if (!material_requirements) {
            return material_requirements;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.production_order = await material_requirements.getProduction_order({
            transaction
        });
        
        
        output.item = await material_requirements.getItem({
            transaction
        });
        
        
        output.uom = await material_requirements.getUom({
            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.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.uoms,
        as: 'uom',
        
        where: filter.uom ? {
          [Op.or]: [
            { id: { [Op.in]: filter.uom.split('|').map(term => Utils.uuid(term)) } },
            {
              name: {
                [Op.or]: filter.uom.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },



    ];

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

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

            
            

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

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

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

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

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

            if (filter.active !== undefined) {
                where = {
                    ...where,
                    active: filter.active === true || filter.active === 'true'
                };
            }

            
            if (filter.issue_method) {
                where = {
                    ...where,
                issue_method: filter.issue_method,
            };
            }
            
            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.material_requirements.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(
                        'material_requirements',
                        'notes',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

