
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,
        
        name: data.name
        ||
        null
            ,
            
        item_number: data.item_number
        ||
        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
            ,
            
        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,
        });
        
        await items.setDefault_warehouse( data.default_warehouse || 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: 'spec_files',
                belongsToId: items.id,
            },
            data.spec_files,
            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,
                
                name: item.name
            ||
            null
            ,
            
                item_number: item.item_number
            ||
            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
            ,
            
                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
        
        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: 'spec_files',
                    belongsToId: items[i].id,
                },
                data[i].spec_files,
                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.name !== undefined) updatePayload.name = data.name;
        
        
        if (data.item_number !== undefined) updatePayload.item_number = data.item_number;
        
        
        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.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 }
            );
        }
        
        if (data.default_warehouse !== undefined) {
            await items.setDefault_warehouse(
              
              data.default_warehouse,
              
              { transaction }
            );
        }
        

        
        

        
        await FileDBApi.replaceRelationFiles(
            {
                belongsTo: db.items.getTableName(),
                belongsToColumn: 'images',
                belongsToId: items.id,
            },
            data.images,
            options,
        );
        
        await FileDBApi.replaceRelationFiles(
            {
                belongsTo: db.items.getTableName(),
                belongsToColumn: 'spec_files',
                belongsToId: items.id,
            },
            data.spec_files,
            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.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.production_orders_item = await items.getProduction_orders_item({
            transaction
        });
        
        
        
        output.material_requirements_item = await items.getMaterial_requirements_item({
            transaction
        });
        
        
        output.lots_item = await items.getLots_item({
            transaction
        });
        
        
        output.serial_numbers_item = await items.getSerial_numbers_item({
            transaction
        });
        
        
        output.inventory_transactions_item = await items.getInventory_transactions_item({
            transaction
        });
        
        
        output.inspections_item = await items.getInspections_item({
            transaction
        });
        
        
        
        output.nonconformances_item = await items.getNonconformances_item({
            transaction
        });
        
        
        output.quality_holds_item = await items.getQuality_holds_item({
            transaction
        });
        
        
        
        output.documents_item = await items.getDocuments_item({
            transaction
        });
        
        
        
        output.default_uom = await items.getDefault_uom({
            transaction
        });
        
        
        output.default_warehouse = await items.getDefault_warehouse({
            transaction
        });
        
        
        output.images = await items.getImages({
            transaction
        });
        
        
        output.spec_files = await items.getSpec_files({
            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)) } },
            {
              name: {
                [Op.or]: filter.default_uom.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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



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

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

    ];

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

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

    
};

