
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
            ,
            
        material_name: data.material_name
        ||
        null
            ,
            
        material_type: data.material_type
        ||
        null
            ,
            
        standard_cost: data.standard_cost
        ||
        null
            ,
            
        standard_price: data.standard_price
        ||
        null
            ,
            
        planning_method: data.planning_method
        ||
        null
            ,
            
        is_lot_tracked: data.is_lot_tracked
        ||
        false
        
            ,
            
        is_serial_tracked: data.is_serial_tracked
        ||
        false
        
            ,
            
        requires_inspection: data.requires_inspection
        ||
        false
        
            ,
            
        shelf_life_days: data.shelf_life_days
        ||
        null
            ,
            
        specification: data.specification
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await materials.setDefault_uom( data.default_uom || null, {
            transaction,
        });
        
        await materials.setPreferred_supplier( data.preferred_supplier || null, {
            transaction,
        });
        

        

        
        await FileDBApi.replaceRelationFiles(
            {
                belongsTo: db.materials.getTableName(),
                belongsToColumn: 'attachments',
                belongsToId: materials.id,
            },
            data.attachments,
            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
            ,
            
                material_name: item.material_name
            ||
            null
            ,
            
                material_type: item.material_type
            ||
            null
            ,
            
                standard_cost: item.standard_cost
            ||
            null
            ,
            
                standard_price: item.standard_price
            ||
            null
            ,
            
                planning_method: item.planning_method
            ||
            null
            ,
            
                is_lot_tracked: item.is_lot_tracked
            ||
            false
        
            ,
            
                is_serial_tracked: item.is_serial_tracked
            ||
            false
        
            ,
            
                requires_inspection: item.requires_inspection
            ||
            false
        
            ,
            
                shelf_life_days: item.shelf_life_days
            ||
            null
            ,
            
                specification: item.specification
            ||
            null
            ,
            
                status: item.status
            ||
            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: 'attachments',
                    belongsToId: materials[i].id,
                },
                data[i].attachments,
                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.material_name !== undefined) updatePayload.material_name = data.material_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_price !== undefined) updatePayload.standard_price = data.standard_price;
        
        
        if (data.planning_method !== undefined) updatePayload.planning_method = data.planning_method;
        
        
        if (data.is_lot_tracked !== undefined) updatePayload.is_lot_tracked = data.is_lot_tracked;
        
        
        if (data.is_serial_tracked !== undefined) updatePayload.is_serial_tracked = data.is_serial_tracked;
        
        
        if (data.requires_inspection !== undefined) updatePayload.requires_inspection = data.requires_inspection;
        
        
        if (data.shelf_life_days !== undefined) updatePayload.shelf_life_days = data.shelf_life_days;
        
        
        if (data.specification !== undefined) updatePayload.specification = data.specification;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.default_uom !== undefined) {
            await materials.setDefault_uom(
              
              data.default_uom,
              
              { transaction }
            );
        }
        
        if (data.preferred_supplier !== undefined) {
            await materials.setPreferred_supplier(
              
              data.preferred_supplier,
              
              { transaction }
            );
        }
        

        
        

        
        await FileDBApi.replaceRelationFiles(
            {
                belongsTo: db.materials.getTableName(),
                belongsToColumn: 'attachments',
                belongsToId: materials.id,
            },
            data.attachments,
            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.material_revisions_material = await materials.getMaterial_revisions_material({
            transaction
        });
        
        
        output.boms_parent_material = await materials.getBoms_parent_material({
            transaction
        });
        
        
        output.bom_lines_component_material = await materials.getBom_lines_component_material({
            transaction
        });
        
        
        output.routings_material = await materials.getRoutings_material({
            transaction
        });
        
        
        
        
        
        
        
        
        output.production_orders_material = await materials.getProduction_orders_material({
            transaction
        });
        
        
        
        output.inventory_lots_material = await materials.getInventory_lots_material({
            transaction
        });
        
        
        output.inventory_transactions_material = await materials.getInventory_transactions_material({
            transaction
        });
        
        
        
        output.purchase_order_lines_material = await materials.getPurchase_order_lines_material({
            transaction
        });
        
        
        output.quality_standards_material = await materials.getQuality_standards_material({
            transaction
        });
        
        
        
        output.inspections_material = await materials.getInspections_material({
            transaction
        });
        
        
        output.nonconformances_material = await materials.getNonconformances_material({
            transaction
        });
        
        
        
        
        
        
        output.default_uom = await materials.getDefault_uom({
            transaction
        });
        
        
        output.preferred_supplier = await materials.getPreferred_supplier({
            transaction
        });
        
        
        output.attachments = await materials.getAttachments({
            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: 'default_uom',
        
        where: filter.default_uom ? {
          [Op.or]: [
            { id: { [Op.in]: filter.default_uom.split('|').map(term => Utils.uuid(term)) } },
            {
              uom_code: {
                [Op.or]: filter.default_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)) } },
            {
              supplier_name: {
                [Op.or]: filter.preferred_supplier.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },



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

    ];

        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.material_name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'materials',
                        'material_name',
                        filter.material_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_priceRange) {
                const [start, end] = filter.standard_priceRange;

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

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

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    shelf_life_days: {
                    ...where.shelf_life_days,
                            [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.planning_method) {
                where = {
                    ...where,
                planning_method: filter.planning_method,
            };
            }
            
            if (filter.is_lot_tracked) {
                where = {
                    ...where,
                is_lot_tracked: filter.is_lot_tracked,
            };
            }
            
            if (filter.is_serial_tracked) {
                where = {
                    ...where,
                is_serial_tracked: filter.is_serial_tracked,
            };
            }
            
            if (filter.requires_inspection) {
                where = {
                    ...where,
                requires_inspection: filter.requires_inspection,
            };
            }
            
            if (filter.status) {
                where = {
                    ...where,
                status: filter.status,
            };
            }
            


      

      



            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',
                        'material_name',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

