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

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

        const bom_items = await db.bom_items.create(
            {
                id: data.id || undefined,
        
        quantity_per: data.quantity_per
        ||
        null
            ,
            
        scrap_factor: data.scrap_factor
        ||
        null
            ,
            
        reference_designator: data.reference_designator
        ||
        null
            ,
            
        notes: data.notes
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await bom_items.setBom( data.bom || null, {
            transaction,
        });
        
        await bom_items.setComponent_material( data.component_material || null, {
            transaction,
        });
        

        

        

        return bom_items;
    }
    

    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 bom_itemsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                quantity_per: item.quantity_per
            ||
            null
            ,
            
                scrap_factor: item.scrap_factor
            ||
            null
            ,
            
                reference_designator: item.reference_designator
            ||
            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 bom_items = await db.bom_items.bulkCreate(bom_itemsData, { transaction });

        // For each item created, replace relation files
        

        return bom_items;
    }

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

        const bom_items = await db.bom_items.findByPk(id, {}, {transaction});


        

        const updatePayload = {};
        
        if (data.quantity_per !== undefined) updatePayload.quantity_per = data.quantity_per;
        
        
        if (data.scrap_factor !== undefined) updatePayload.scrap_factor = data.scrap_factor;
        
        
        if (data.reference_designator !== undefined) updatePayload.reference_designator = data.reference_designator;
        
        
        if (data.notes !== undefined) updatePayload.notes = data.notes;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.bom !== undefined) {
            await bom_items.setBom(
              
              data.bom,
              
              { transaction }
            );
        }
        
        if (data.component_material !== undefined) {
            await bom_items.setComponent_material(
              
              data.component_material,
              
              { transaction }
            );
        }
        

        
        

        

        return bom_items;
    }

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

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

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


        return bom_items;
    }

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

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

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

        await bom_items.destroy({
            transaction
        });

        return bom_items;
    }

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

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

        if (!bom_items) {
            return bom_items;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.bom = await bom_items.getBom({
            transaction
        });
        
        
        output.component_material = await bom_items.getComponent_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 = [

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

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



    ];

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

            
            if (filter.reference_designator) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'bom_items',
                        'reference_designator',
                        filter.reference_designator,
                    ),
                };
            }
            
            if (filter.notes) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'bom_items',
                        'notes',
                        filter.notes,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

            


      

      



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

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

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

    
};

