
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,
        
        material_code: data.material_code
        ||
        null
            ,
            
        name: data.name
        ||
        null
            ,
            
        material_type: data.material_type
        ||
        null
            ,
            
        standard_cost: data.standard_cost
        ||
        null
            ,
            
        standard_lead_time_days: data.standard_lead_time_days
        ||
        null
            ,
            
        lot_tracked: data.lot_tracked
        ||
        false
        
            ,
            
        serial_tracked: data.serial_tracked
        ||
        false
        
            ,
            
        reorder_point: data.reorder_point
        ||
        null
            ,
            
        reorder_quantity: data.reorder_quantity
        ||
        null
            ,
            
        specification: data.specification
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await materials.setUom( data.uom || null, {
            transaction,
        });
        
        await materials.setPreferred_supplier( data.preferred_supplier || 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,
                
                material_code: item.material_code
            ||
            null
            ,
            
                name: item.name
            ||
            null
            ,
            
                material_type: item.material_type
            ||
            null
            ,
            
                standard_cost: item.standard_cost
            ||
            null
            ,
            
                standard_lead_time_days: item.standard_lead_time_days
            ||
            null
            ,
            
                lot_tracked: item.lot_tracked
            ||
            false
        
            ,
            
                serial_tracked: item.serial_tracked
            ||
            false
        
            ,
            
                reorder_point: item.reorder_point
            ||
            null
            ,
            
                reorder_quantity: item.reorder_quantity
            ||
            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 materials = await db.materials.findByPk(id, {}, {transaction});


        

        const updatePayload = {};
        
        if (data.material_code !== undefined) updatePayload.material_code = data.material_code;
        
        
        if (data.name !== undefined) updatePayload.name = data.name;
        
        
        if (data.material_type !== undefined) updatePayload.material_type = data.material_type;
        
        
        if (data.standard_cost !== undefined) updatePayload.standard_cost = data.standard_cost;
        
        
        if (data.standard_lead_time_days !== undefined) updatePayload.standard_lead_time_days = data.standard_lead_time_days;
        
        
        if (data.lot_tracked !== undefined) updatePayload.lot_tracked = data.lot_tracked;
        
        
        if (data.serial_tracked !== undefined) updatePayload.serial_tracked = data.serial_tracked;
        
        
        if (data.reorder_point !== undefined) updatePayload.reorder_point = data.reorder_point;
        
        
        if (data.reorder_quantity !== undefined) updatePayload.reorder_quantity = data.reorder_quantity;
        
        
        if (data.specification !== undefined) updatePayload.specification = data.specification;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.uom !== undefined) {
            await materials.setUom(
              
              data.uom,
              
              { transaction }
            );
        }
        
        if (data.preferred_supplier !== undefined) {
            await materials.setPreferred_supplier(
              
              data.preferred_supplier,
              
              { 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_lots_material = await materials.getInventory_lots_material({
            transaction
        });
        
        
        output.inventory_balances_material = await materials.getInventory_balances_material({
            transaction
        });
        
        
        output.inventory_transactions_material = await materials.getInventory_transactions_material({
            transaction
        });
        
        
        output.boms_parent_material = await materials.getBoms_parent_material({
            transaction
        });
        
        
        output.bom_items_component_material = await materials.getBom_items_component_material({
            transaction
        });
        
        
        output.routings_material = await materials.getRoutings_material({
            transaction
        });
        
        
        
        output.production_orders_material = await materials.getProduction_orders_material({
            transaction
        });
        
        
        
        output.production_material_issues_material = await materials.getProduction_material_issues_material({
            transaction
        });
        
        
        
        output.qa_inspections_material = await materials.getQa_inspections_material({
            transaction
        });
        
        
        
        
        
        output.nonconformances_material = await materials.getNonconformances_material({
            transaction
        });
        
        
        
        
        
        output.uom = await materials.getUom({
            transaction
        });
        
        
        output.preferred_supplier = await materials.getPreferred_supplier({
            transaction
        });
        
        
        output.spec_files = await materials.getSpec_files({
            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.units_of_measure,
        as: 'uom',
        
        where: filter.uom ? {
          [Op.or]: [
            { id: { [Op.in]: filter.uom.split('|').map(term => Utils.uuid(term)) } },
            {
              code: {
                [Op.or]: filter.uom.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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



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

    ];

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

            
            if (filter.material_code) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'materials',
                        'material_code',
                        filter.material_code,
                    ),
                };
            }
            
            if (filter.name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'materials',
                        'name',
                        filter.name,
                    ),
                };
            }
            
            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.standard_lead_time_daysRange) {
                const [start, end] = filter.standard_lead_time_daysRange;

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    standard_lead_time_days: {
                    ...where.standard_lead_time_days,
                            [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.lot_tracked) {
                where = {
                    ...where,
                lot_tracked: filter.lot_tracked,
            };
            }
            
            if (filter.serial_tracked) {
                where = {
                    ...where,
                serial_tracked: filter.serial_tracked,
            };
            }
            


      

      



            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.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(
                        '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,
        }));
    }

    
};

