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

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

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

        
        await material_issues.setWork_order( data.work_order || null, {
            transaction,
        });
        
        await material_issues.setItem( data.item || null, {
            transaction,
        });
        
        await material_issues.setLot( data.lot || null, {
            transaction,
        });
        
        await material_issues.setFrom_location( data.from_location || null, {
            transaction,
        });
        
        await material_issues.setIssued_by_user( data.issued_by_user || null, {
            transaction,
        });
        
        await material_issues.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

        

        return material_issues;
    }
    

    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_issuesData = data.map((item, index) => ({
                id: item.id || undefined,
                
                quantity_issued: item.quantity_issued
            ||
            null
            ,
            
                uom: item.uom
            ||
            null
            ,
            
                issued_at: item.issued_at
            ||
            null
            ,
            
                issue_method: item.issue_method
            ||
            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_issues = await db.material_issues.bulkCreate(material_issuesData, { transaction });

        // For each item created, replace relation files
        

        return material_issues;
    }

    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 material_issues = await db.material_issues.findByPk(id, {}, {transaction});


        

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

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

        
        
        if (data.work_order !== undefined) {
            await material_issues.setWork_order(
              
              data.work_order,
              
              { transaction }
            );
        }
        
        if (data.item !== undefined) {
            await material_issues.setItem(
              
              data.item,
              
              { transaction }
            );
        }
        
        if (data.lot !== undefined) {
            await material_issues.setLot(
              
              data.lot,
              
              { transaction }
            );
        }
        
        if (data.from_location !== undefined) {
            await material_issues.setFrom_location(
              
              data.from_location,
              
              { transaction }
            );
        }
        
        if (data.issued_by_user !== undefined) {
            await material_issues.setIssued_by_user(
              
              data.issued_by_user,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await material_issues.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        

        

        return material_issues;
    }

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

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

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


        return material_issues;
    }

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

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

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

        await material_issues.destroy({
            transaction
        });

        return material_issues;
    }

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

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

        if (!material_issues) {
            return material_issues;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.work_order = await material_issues.getWork_order({
            transaction
        });
        
        
        output.item = await material_issues.getItem({
            transaction
        });
        
        
        output.lot = await material_issues.getLot({
            transaction
        });
        
        
        output.from_location = await material_issues.getFrom_location({
            transaction
        });
        
        
        output.issued_by_user = await material_issues.getIssued_by_user({
            transaction
        });
        
        
        output.organizations = await material_issues.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.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.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)) } },
            {
              code: {
                [Op.or]: filter.from_location.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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

            
            

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

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

    
};

