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

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

        const materials = await db.materials.create(
            {
                id: data.id || undefined,
        
        sku: data.sku
        ||
        null
            ,
            
        name: data.name
        ||
        null
            ,
            
        material_type: data.material_type
        ||
        null
            ,
            
        unit_of_measure: data.unit_of_measure
        ||
        null
            ,
            
        standard_cost: data.standard_cost
        ||
        null
            ,
            
        reorder_point: data.reorder_point
        ||
        null
            ,
            
        reorder_quantity: data.reorder_quantity
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        specification: data.specification
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await materials.setPreferred_vendor( data.preferred_vendor || null, {
            transaction,
        });
        
        await materials.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

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

        return 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 materialsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                sku: item.sku
            ||
            null
            ,
            
                name: item.name
            ||
            null
            ,
            
                material_type: item.material_type
            ||
            null
            ,
            
                unit_of_measure: item.unit_of_measure
            ||
            null
            ,
            
                standard_cost: item.standard_cost
            ||
            null
            ,
            
                reorder_point: item.reorder_point
            ||
            null
            ,
            
                reorder_quantity: item.reorder_quantity
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
                specification: item.specification
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

        // Bulk create items
        const materials = await db.materials.bulkCreate(materialsData, { transaction });

        // For each item created, replace relation files
        
        for (let i = 0; i < materials.length; i++) {
            await FileDBApi.replaceRelationFiles(
                {
                    belongsTo: db.materials.getTableName(),
                    belongsToColumn: 'spec_files',
                    belongsToId: materials[i].id,
                },
                data[i].spec_files,
                options,
            );
        }
        

        return materials;
    }

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


        

        const updatePayload = {};
        
        if (data.sku !== undefined) updatePayload.sku = data.sku;
        
        
        if (data.name !== undefined) updatePayload.name = data.name;
        
        
        if (data.material_type !== undefined) updatePayload.material_type = data.material_type;
        
        
        if (data.unit_of_measure !== undefined) updatePayload.unit_of_measure = data.unit_of_measure;
        
        
        if (data.standard_cost !== undefined) updatePayload.standard_cost = data.standard_cost;
        
        
        if (data.reorder_point !== undefined) updatePayload.reorder_point = data.reorder_point;
        
        
        if (data.reorder_quantity !== undefined) updatePayload.reorder_quantity = data.reorder_quantity;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.specification !== undefined) updatePayload.specification = data.specification;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.preferred_vendor !== undefined) {
            await materials.setPreferred_vendor(
              
              data.preferred_vendor,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await materials.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        

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

        return materials;
    }

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

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

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


        return materials;
    }

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

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

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

        await materials.destroy({
            transaction
        });

        return materials;
    }

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

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

        if (!materials) {
            return materials;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.inventory_items_material = await materials.getInventory_items_material({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.preferred_vendor = await materials.getPreferred_vendor({
            transaction
        });
        
        
        output.spec_files = await materials.getSpec_files({
            transaction
        });
        
        
        output.organizations = await materials.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.vendors,
        as: 'preferred_vendor',
        
        where: filter.preferred_vendor ? {
          [Op.or]: [
            { id: { [Op.in]: filter.preferred_vendor.split('|').map(term => Utils.uuid(term)) } },
            {
              name: {
                [Op.or]: filter.preferred_vendor.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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



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

    ];

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

            
            if (filter.sku) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'materials',
                        'sku',
                        filter.sku,
                    ),
                };
            }
            
            if (filter.name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'materials',
                        'name',
                        filter.name,
                    ),
                };
            }
            
            if (filter.unit_of_measure) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'materials',
                        'unit_of_measure',
                        filter.unit_of_measure,
                    ),
                };
            }
            
            if (filter.specification) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'materials',
                        'specification',
                        filter.specification,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

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

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

            
            if (filter.material_type) {
                where = {
                    ...where,
                material_type: filter.material_type,
            };
            }
            
            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.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,  globalAccess, organizationId,) {
        let where = {};
        
        
        if (!globalAccess && organizationId) {
            where.organizationId = organizationId;
        }
        

        if (query) {
            where = {
                [Op.or]: [
                    { ['id']: Utils.uuid(query) },
                    Utils.ilike(
                        'materials',
                        'name',
                        query,
                    ),
                ],
            };
        }

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

    
};

