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

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

        const work_order_materials = await db.work_order_materials.create(
            {
                id: data.id || undefined,
        
        required_qty: data.required_qty
        ||
        null
            ,
            
        issued_qty: data.issued_qty
        ||
        null
            ,
            
        scrap_qty: data.scrap_qty
        ||
        null
            ,
            
        notes: data.notes
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await work_order_materials.setWork_order( data.work_order || null, {
            transaction,
        });
        
        await work_order_materials.setMaterial( data.material || null, {
            transaction,
        });
        

        

        

        return work_order_materials;
    }
    

    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 work_order_materialsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                required_qty: item.required_qty
            ||
            null
            ,
            
                issued_qty: item.issued_qty
            ||
            null
            ,
            
                scrap_qty: item.scrap_qty
            ||
            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 work_order_materials = await db.work_order_materials.bulkCreate(work_order_materialsData, { transaction });

        // For each item created, replace relation files
        

        return work_order_materials;
    }

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

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


        

        const updatePayload = {};
        
        if (data.required_qty !== undefined) updatePayload.required_qty = data.required_qty;
        
        
        if (data.issued_qty !== undefined) updatePayload.issued_qty = data.issued_qty;
        
        
        if (data.scrap_qty !== undefined) updatePayload.scrap_qty = data.scrap_qty;
        
        
        if (data.notes !== undefined) updatePayload.notes = data.notes;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.work_order !== undefined) {
            await work_order_materials.setWork_order(
              
              data.work_order,
              
              { transaction }
            );
        }
        
        if (data.material !== undefined) {
            await work_order_materials.setMaterial(
              
              data.material,
              
              { transaction }
            );
        }
        

        
        

        

        return work_order_materials;
    }

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

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

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


        return work_order_materials;
    }

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

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

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

        await work_order_materials.destroy({
            transaction
        });

        return work_order_materials;
    }

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

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

        if (!work_order_materials) {
            return work_order_materials;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.work_order = await work_order_materials.getWork_order({
            transaction
        });
        
        
        output.material = await work_order_materials.getMaterial({
            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.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.materials,
        as: 'material',
        
        where: filter.material ? {
          [Op.or]: [
            { id: { [Op.in]: filter.material.split('|').map(term => Utils.uuid(term)) } },
            {
              name: {
                [Op.or]: filter.material.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(
                        'work_order_materials',
                        'notes',
                        filter.notes,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

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

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

            


      

      



            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.work_order_materials.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(
                        'work_order_materials',
                        'material',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

