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

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

        const items = await db.items.create(
            {
                id: data.id || undefined,
        
        item_name: data.item_name
        ||
        null
            ,
            
        item_code: data.item_code
        ||
        null
            ,
            
        item_type: data.item_type
        ||
        null
            ,
            
        lot_tracked: data.lot_tracked
        ||
        false
        
            ,
            
        serial_tracked: data.serial_tracked
        ||
        false
        
            ,
            
        standard_cost: data.standard_cost
        ||
        null
            ,
            
        shelf_life_days: data.shelf_life_days
        ||
        null
            ,
            
        description: data.description
        ||
        null
            ,
            
        active: data.active
        ||
        false
        
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await items.setDefault_uom( data.default_uom || null, {
            transaction,
        });
        

        

        

        return 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 itemsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                item_name: item.item_name
            ||
            null
            ,
            
                item_code: item.item_code
            ||
            null
            ,
            
                item_type: item.item_type
            ||
            null
            ,
            
                lot_tracked: item.lot_tracked
            ||
            false
        
            ,
            
                serial_tracked: item.serial_tracked
            ||
            false
        
            ,
            
                standard_cost: item.standard_cost
            ||
            null
            ,
            
                shelf_life_days: item.shelf_life_days
            ||
            null
            ,
            
                description: item.description
            ||
            null
            ,
            
                active: item.active
            ||
            false
        
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return items;
    }

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

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


        

        const updatePayload = {};
        
        if (data.item_name !== undefined) updatePayload.item_name = data.item_name;
        
        
        if (data.item_code !== undefined) updatePayload.item_code = data.item_code;
        
        
        if (data.item_type !== undefined) updatePayload.item_type = data.item_type;
        
        
        if (data.lot_tracked !== undefined) updatePayload.lot_tracked = data.lot_tracked;
        
        
        if (data.serial_tracked !== undefined) updatePayload.serial_tracked = data.serial_tracked;
        
        
        if (data.standard_cost !== undefined) updatePayload.standard_cost = data.standard_cost;
        
        
        if (data.shelf_life_days !== undefined) updatePayload.shelf_life_days = data.shelf_life_days;
        
        
        if (data.description !== undefined) updatePayload.description = data.description;
        
        
        if (data.active !== undefined) updatePayload.active = data.active;
        
        
        updatePayload.updatedById = currentUser.id;

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

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

        
        

        

        return items;
    }

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

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

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


        return items;
    }

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

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

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

        await items.destroy({
            transaction
        });

        return items;
    }

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

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

        if (!items) {
            return items;
        }

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

        
        
        
        
        
        
        
        
        
        
        output.approved_vendors_item = await items.getApproved_vendors_item({
            transaction
        });
        
        
        output.boms_parent_item = await items.getBoms_parent_item({
            transaction
        });
        
        
        output.bom_lines_component_item = await items.getBom_lines_component_item({
            transaction
        });
        
        
        output.routings_item = await items.getRoutings_item({
            transaction
        });
        
        
        
        
        
        
        
        output.work_orders_item = await items.getWork_orders_item({
            transaction
        });
        
        
        
        output.lots_item = await items.getLots_item({
            transaction
        });
        
        
        output.serials_item = await items.getSerials_item({
            transaction
        });
        
        
        output.inventory_balances_item = await items.getInventory_balances_item({
            transaction
        });
        
        
        output.inventory_movements_item = await items.getInventory_movements_item({
            transaction
        });
        
        
        
        output.purchase_order_lines_item = await items.getPurchase_order_lines_item({
            transaction
        });
        
        
        output.inspection_plans_item = await items.getInspection_plans_item({
            transaction
        });
        
        
        
        output.inspections_item = await items.getInspections_item({
            transaction
        });
        
        
        
        output.nonconformances_item = await items.getNonconformances_item({
            transaction
        });
        
        
        
        
        
        
        output.default_uom = await items.getDefault_uom({
            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.uoms,
        as: 'default_uom',
        
        where: filter.default_uom ? {
          [Op.or]: [
            { id: { [Op.in]: filter.default_uom.split('|').map(term => Utils.uuid(term)) } },
            {
              uom_name: {
                [Op.or]: filter.default_uom.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },



    ];

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

            
            if (filter.item_name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'items',
                        'item_name',
                        filter.item_name,
                    ),
                };
            }
            
            if (filter.item_code) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'items',
                        'item_code',
                        filter.item_code,
                    ),
                };
            }
            
            if (filter.description) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'items',
                        'description',
                        filter.description,
                    ),
                };
            }
            

            
            

            
            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.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.item_type) {
                where = {
                    ...where,
                item_type: filter.item_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.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.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(
                        'items',
                        'item_name',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

