
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
            ,
            
        category: data.category
        ||
        null
            ,
            
        uom: data.uom
        ||
        null
            ,
            
        standard_cost: data.standard_cost
        ||
        null
            ,
            
        last_cost: data.last_cost
        ||
        null
            ,
            
        sale_price: data.sale_price
        ||
        null
            ,
            
        reorder_point: data.reorder_point
        ||
        null
            ,
            
        stocked: data.stocked
        ||
        false
        
            ,
            
        active: data.active
        ||
        false
        
            ,
            
        notes: data.notes
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        

        

        

        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
            ,
            
                category: item.category
            ||
            null
            ,
            
                uom: item.uom
            ||
            null
            ,
            
                standard_cost: item.standard_cost
            ||
            null
            ,
            
                last_cost: item.last_cost
            ||
            null
            ,
            
                sale_price: item.sale_price
            ||
            null
            ,
            
                reorder_point: item.reorder_point
            ||
            null
            ,
            
                stocked: item.stocked
            ||
            false
        
            ,
            
                active: item.active
            ||
            false
        
            ,
            
                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 materials = await db.materials.bulkCreate(materialsData, { transaction });

        // For each item created, replace relation files
        

        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.category !== undefined) updatePayload.category = data.category;
        
        
        if (data.uom !== undefined) updatePayload.uom = data.uom;
        
        
        if (data.standard_cost !== undefined) updatePayload.standard_cost = data.standard_cost;
        
        
        if (data.last_cost !== undefined) updatePayload.last_cost = data.last_cost;
        
        
        if (data.sale_price !== undefined) updatePayload.sale_price = data.sale_price;
        
        
        if (data.reorder_point !== undefined) updatePayload.reorder_point = data.reorder_point;
        
        
        if (data.stocked !== undefined) updatePayload.stocked = data.stocked;
        
        
        if (data.active !== undefined) updatePayload.active = data.active;
        
        
        if (data.notes !== undefined) updatePayload.notes = data.notes;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        

        
        

        

        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.inventory_transactions_material = await materials.getInventory_transactions_material({
            transaction
        });
        
        
        
        output.bom_items_material = await materials.getBom_items_material({
            transaction
        });
        
        
        
        output.purchase_order_line_items_material = await materials.getPurchase_order_line_items_material({
            transaction
        });
        
        
        
        
        output.work_order_materials_material = await materials.getWork_order_materials_material({
            transaction
        });
        
        
        
        output.delivery_items_material = await materials.getDelivery_items_material({
            transaction
        });
        
        
        
        output.invoice_line_items_material = await materials.getInvoice_line_items_material({
            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 = [



    ];

        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.uom) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'materials',
                        'uom',
                        filter.uom,
                    ),
                };
            }
            
            if (filter.notes) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'materials',
                        'notes',
                        filter.notes,
                    ),
                };
            }
            

            
            

            
            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.last_costRange) {
                const [start, end] = filter.last_costRange;

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

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

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

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

            
            if (filter.category) {
                where = {
                    ...where,
                category: filter.category,
            };
            }
            
            if (filter.stocked) {
                where = {
                    ...where,
                stocked: filter.stocked,
            };
            }
            
            if (filter.active) {
                where = {
                    ...where,
                active: filter.active,
            };
            }
            




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

    
};

