
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_code: data.item_code
        ||
        null
            ,
            
        name: data.name
        ||
        null
            ,
            
        item_type: data.item_type
        ||
        null
            ,
            
        tracking: data.tracking
        ||
        null
            ,
            
        default_scrap_rate: data.default_scrap_rate
        ||
        null
            ,
            
        shelf_life_days: data.shelf_life_days
        ||
        null
            ,
            
        is_active: data.is_active
        ||
        false
        
            ,
            
        description: data.description
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await items.setUom( data.uom || null, {
            transaction,
        });
        

        

        
        await FileDBApi.replaceRelationFiles(
            {
                belongsTo: db.items.getTableName(),
                belongsToColumn: 'images',
                belongsToId: items.id,
            },
            data.images,
            options,
        );
        
        await FileDBApi.replaceRelationFiles(
            {
                belongsTo: db.items.getTableName(),
                belongsToColumn: 'attachments',
                belongsToId: items.id,
            },
            data.attachments,
            options,
        );
        

        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_code: item.item_code
            ||
            null
            ,
            
                name: item.name
            ||
            null
            ,
            
                item_type: item.item_type
            ||
            null
            ,
            
                tracking: item.tracking
            ||
            null
            ,
            
                default_scrap_rate: item.default_scrap_rate
            ||
            null
            ,
            
                shelf_life_days: item.shelf_life_days
            ||
            null
            ,
            
                is_active: item.is_active
            ||
            false
        
            ,
            
                description: item.description
            ||
            null
            ,
            
            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
        
        for (let i = 0; i < items.length; i++) {
            await FileDBApi.replaceRelationFiles(
                {
                    belongsTo: db.items.getTableName(),
                    belongsToColumn: 'images',
                    belongsToId: items[i].id,
                },
                data[i].images,
                options,
            );
        }
        
        for (let i = 0; i < items.length; i++) {
            await FileDBApi.replaceRelationFiles(
                {
                    belongsTo: db.items.getTableName(),
                    belongsToColumn: 'attachments',
                    belongsToId: items[i].id,
                },
                data[i].attachments,
                options,
            );
        }
        

        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_code !== undefined) updatePayload.item_code = data.item_code;
        
        
        if (data.name !== undefined) updatePayload.name = data.name;
        
        
        if (data.item_type !== undefined) updatePayload.item_type = data.item_type;
        
        
        if (data.tracking !== undefined) updatePayload.tracking = data.tracking;
        
        
        if (data.default_scrap_rate !== undefined) updatePayload.default_scrap_rate = data.default_scrap_rate;
        
        
        if (data.shelf_life_days !== undefined) updatePayload.shelf_life_days = data.shelf_life_days;
        
        
        if (data.is_active !== undefined) updatePayload.is_active = data.is_active;
        
        
        if (data.description !== undefined) updatePayload.description = data.description;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.uom !== undefined) {
            await items.setUom(
              
              data.uom,
              
              { transaction }
            );
        }
        

        
        

        
        await FileDBApi.replaceRelationFiles(
            {
                belongsTo: db.items.getTableName(),
                belongsToColumn: 'images',
                belongsToId: items.id,
            },
            data.images,
            options,
        );
        
        await FileDBApi.replaceRelationFiles(
            {
                belongsTo: db.items.getTableName(),
                belongsToColumn: 'attachments',
                belongsToId: items.id,
            },
            data.attachments,
            options,
        );
        

        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.item_supplier_links_item = await items.getItem_supplier_links_item({
            transaction
        });
        
        
        
        
        output.inventory_lots_item = await items.getInventory_lots_item({
            transaction
        });
        
        
        output.inventory_balances_item = await items.getInventory_balances_item({
            transaction
        });
        
        
        output.inventory_transactions_item = await items.getInventory_transactions_item({
            transaction
        });
        
        
        output.bom_headers_item = await items.getBom_headers_item({
            transaction
        });
        
        
        output.bom_lines_component_item = await items.getBom_lines_component_item({
            transaction
        });
        
        
        
        
        output.routing_headers_item = await items.getRouting_headers_item({
            transaction
        });
        
        
        
        output.production_orders_item = await items.getProduction_orders_item({
            transaction
        });
        
        
        
        output.material_issues_item = await items.getMaterial_issues_item({
            transaction
        });
        
        
        output.production_receipts_item = await items.getProduction_receipts_item({
            transaction
        });
        
        
        output.qa_inspection_plans_item = await items.getQa_inspection_plans_item({
            transaction
        });
        
        
        output.qa_inspections_item = await items.getQa_inspections_item({
            transaction
        });
        
        
        output.nonconformances_item = await items.getNonconformances_item({
            transaction
        });
        
        
        
        
        
        output.purchase_order_lines_item = await items.getPurchase_order_lines_item({
            transaction
        });
        
        
        
        output.sales_order_lines_item = await items.getSales_order_lines_item({
            transaction
        });
        
        
        
        output.shipment_lines_item = await items.getShipment_lines_item({
            transaction
        });
        
        
        
        
        output.standard_costs_item = await items.getStandard_costs_item({
            transaction
        });
        
        
        
        
        output.price_list_lines_item = await items.getPrice_list_lines_item({
            transaction
        });
        
        
        
        
        output.uom = await items.getUom({
            transaction
        });
        
        
        output.images = await items.getImages({
            transaction
        });
        
        
        output.attachments = await items.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.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}%` }))
              }
            },
          ]
        } : {},
        
      },



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

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

    ];

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

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

            
            

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

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    default_scrap_rate: {
                    ...where.default_scrap_rate,
                            [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.tracking) {
                where = {
                    ...where,
                tracking: filter.tracking,
            };
            }
            
            if (filter.is_active) {
                where = {
                    ...where,
                is_active: filter.is_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',
                        'name',
                        query,
                    ),
                ],
            };
        }

        const records = await db.items.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,
        }));
    }

    
};

