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

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

        const bom_lines = await db.bom_lines.create(
            {
                id: data.id || undefined,
        
        line_number: data.line_number
        ||
        null
            ,
            
        quantity_per: data.quantity_per
        ||
        null
            ,
            
        scrap_rate: data.scrap_rate
        ||
        null
            ,
            
        issue_method: data.issue_method
        ||
        null
            ,
            
        remarks: data.remarks
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await bom_lines.setBom_header( data.bom_header || null, {
            transaction,
        });
        
        await bom_lines.setComponent_item( data.component_item || null, {
            transaction,
        });
        
        await bom_lines.setUom( data.uom || null, {
            transaction,
        });
        

        

        

        return bom_lines;
    }
    

    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_linesData = data.map((item, index) => ({
                id: item.id || undefined,
                
                line_number: item.line_number
            ||
            null
            ,
            
                quantity_per: item.quantity_per
            ||
            null
            ,
            
                scrap_rate: item.scrap_rate
            ||
            null
            ,
            
                issue_method: item.issue_method
            ||
            null
            ,
            
                remarks: item.remarks
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return bom_lines;
    }

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

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


        

        const updatePayload = {};
        
        if (data.line_number !== undefined) updatePayload.line_number = data.line_number;
        
        
        if (data.quantity_per !== undefined) updatePayload.quantity_per = data.quantity_per;
        
        
        if (data.scrap_rate !== undefined) updatePayload.scrap_rate = data.scrap_rate;
        
        
        if (data.issue_method !== undefined) updatePayload.issue_method = data.issue_method;
        
        
        if (data.remarks !== undefined) updatePayload.remarks = data.remarks;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.bom_header !== undefined) {
            await bom_lines.setBom_header(
              
              data.bom_header,
              
              { transaction }
            );
        }
        
        if (data.component_item !== undefined) {
            await bom_lines.setComponent_item(
              
              data.component_item,
              
              { transaction }
            );
        }
        
        if (data.uom !== undefined) {
            await bom_lines.setUom(
              
              data.uom,
              
              { transaction }
            );
        }
        

        
        

        

        return bom_lines;
    }

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

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

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


        return bom_lines;
    }

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

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

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

        await bom_lines.destroy({
            transaction
        });

        return bom_lines;
    }

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

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

        if (!bom_lines) {
            return bom_lines;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.bom_header = await bom_lines.getBom_header({
            transaction
        });
        
        
        output.component_item = await bom_lines.getComponent_item({
            transaction
        });
        
        
        output.uom = await bom_lines.getUom({
            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.bom_headers,
        as: 'bom_header',
        
        where: filter.bom_header ? {
          [Op.or]: [
            { id: { [Op.in]: filter.bom_header.split('|').map(term => Utils.uuid(term)) } },
            {
              bom_code: {
                [Op.or]: filter.bom_header.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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

      {
        model: db.uoms,
        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}%` }))
              }
            },
          ]
        } : {},
        
      },



    ];

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

            
            if (filter.remarks) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'bom_lines',
                        'remarks',
                        filter.remarks,
                    ),
                };
            }
            

            
            

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

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    line_number: {
                    ...where.line_number,
                            [Op.lte]: end,
                    },
                };
                }
            }
            
            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_rateRange) {
                const [start, end] = filter.scrap_rateRange;

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

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

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

            
            if (filter.issue_method) {
                where = {
                    ...where,
                issue_method: filter.issue_method,
            };
            }
            


      

      

      



            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_lines.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_lines',
                        'remarks',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

