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

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

        const production_materials = await db.production_materials.create(
            {
                id: data.id || undefined,
        
        issue_method: data.issue_method
        ||
        null
            ,
            
        quantity_required: data.quantity_required
        ||
        null
            ,
            
        quantity_issued: data.quantity_issued
        ||
        null
            ,
            
        issued_at: data.issued_at
        ||
        null
            ,
            
        notes: data.notes
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await production_materials.setProduction_order( data.production_order || null, {
            transaction,
        });
        
        await production_materials.setComponent_item( data.component_item || null, {
            transaction,
        });
        
        await production_materials.setLot( data.lot || null, {
            transaction,
        });
        
        await production_materials.setFrom_location( data.from_location || null, {
            transaction,
        });
        
        await production_materials.setIssued_by( data.issued_by || null, {
            transaction,
        });
        

        

        

        return production_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 production_materialsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                issue_method: item.issue_method
            ||
            null
            ,
            
                quantity_required: item.quantity_required
            ||
            null
            ,
            
                quantity_issued: item.quantity_issued
            ||
            null
            ,
            
                issued_at: item.issued_at
            ||
            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 production_materials = await db.production_materials.bulkCreate(production_materialsData, { transaction });

        // For each item created, replace relation files
        

        return production_materials;
    }

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

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


        

        const updatePayload = {};
        
        if (data.issue_method !== undefined) updatePayload.issue_method = data.issue_method;
        
        
        if (data.quantity_required !== undefined) updatePayload.quantity_required = data.quantity_required;
        
        
        if (data.quantity_issued !== undefined) updatePayload.quantity_issued = data.quantity_issued;
        
        
        if (data.issued_at !== undefined) updatePayload.issued_at = data.issued_at;
        
        
        if (data.notes !== undefined) updatePayload.notes = data.notes;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.production_order !== undefined) {
            await production_materials.setProduction_order(
              
              data.production_order,
              
              { transaction }
            );
        }
        
        if (data.component_item !== undefined) {
            await production_materials.setComponent_item(
              
              data.component_item,
              
              { transaction }
            );
        }
        
        if (data.lot !== undefined) {
            await production_materials.setLot(
              
              data.lot,
              
              { transaction }
            );
        }
        
        if (data.from_location !== undefined) {
            await production_materials.setFrom_location(
              
              data.from_location,
              
              { transaction }
            );
        }
        
        if (data.issued_by !== undefined) {
            await production_materials.setIssued_by(
              
              data.issued_by,
              
              { transaction }
            );
        }
        

        
        

        

        return production_materials;
    }

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

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

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


        return production_materials;
    }

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

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

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

        await production_materials.destroy({
            transaction
        });

        return production_materials;
    }

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

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

        if (!production_materials) {
            return production_materials;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.production_order = await production_materials.getProduction_order({
            transaction
        });
        
        
        output.component_item = await production_materials.getComponent_item({
            transaction
        });
        
        
        output.lot = await production_materials.getLot({
            transaction
        });
        
        
        output.from_location = await production_materials.getFrom_location({
            transaction
        });
        
        
        output.issued_by = await production_materials.getIssued_by({
            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: 'component_item',
        
        where: filter.component_item ? {
          [Op.or]: [
            { id: { [Op.in]: filter.component_item.split('|').map(term => Utils.uuid(term)) } },
            {
              name: {
                [Op.or]: filter.component_item.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

      {
        model: db.inventory_lots,
        as: 'lot',
        
        where: filter.lot ? {
          [Op.or]: [
            { id: { [Op.in]: filter.lot.split('|').map(term => Utils.uuid(term)) } },
            {
              lot_number: {
                [Op.or]: filter.lot.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

      {
        model: db.locations,
        as: 'from_location',
        
        where: filter.from_location ? {
          [Op.or]: [
            { id: { [Op.in]: filter.from_location.split('|').map(term => Utils.uuid(term)) } },
            {
              name: {
                [Op.or]: filter.from_location.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

      {
        model: db.users,
        as: 'issued_by',
        
        where: filter.issued_by ? {
          [Op.or]: [
            { id: { [Op.in]: filter.issued_by.split('|').map(term => Utils.uuid(term)) } },
            {
              firstName: {
                [Op.or]: filter.issued_by.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(
                        'production_materials',
                        'notes',
                        filter.notes,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

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

        const records = await db.production_materials.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,
        }));
    }

    
};

