
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,
        
        sku: data.sku
        ||
        null
            ,
            
        name: data.name
        ||
        null
            ,
            
        description: data.description
        ||
        null
            ,
            
        item_type: data.item_type
        ||
        null
            ,
            
        uom: data.uom
        ||
        null
            ,
            
        is_lot_tracked: data.is_lot_tracked
        ||
        false
        
            ,
            
        requires_expiry: data.requires_expiry
        ||
        false
        
            ,
            
        shelf_life_days: data.shelf_life_days
        ||
        null
            ,
            
        standard_cost: data.standard_cost
        ||
        null
            ,
            
        standard_price: data.standard_price
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await items.setCompany( data.company || null, {
            transaction,
        });
        
        await items.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

        
        await FileDBApi.replaceRelationFiles(
            {
                belongsTo: db.items.getTableName(),
                belongsToColumn: 'spec_documents',
                belongsToId: items.id,
            },
            data.spec_documents,
            options,
        );
        
        await FileDBApi.replaceRelationFiles(
            {
                belongsTo: db.items.getTableName(),
                belongsToColumn: 'images',
                belongsToId: items.id,
            },
            data.images,
            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,
                
                sku: item.sku
            ||
            null
            ,
            
                name: item.name
            ||
            null
            ,
            
                description: item.description
            ||
            null
            ,
            
                item_type: item.item_type
            ||
            null
            ,
            
                uom: item.uom
            ||
            null
            ,
            
                is_lot_tracked: item.is_lot_tracked
            ||
            false
        
            ,
            
                requires_expiry: item.requires_expiry
            ||
            false
        
            ,
            
                shelf_life_days: item.shelf_life_days
            ||
            null
            ,
            
                standard_cost: item.standard_cost
            ||
            null
            ,
            
                standard_price: item.standard_price
            ||
            null
            ,
            
                status: item.status
            ||
            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: 'spec_documents',
                    belongsToId: items[i].id,
                },
                data[i].spec_documents,
                options,
            );
        }
        
        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,
            );
        }
        

        return items;
    }

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

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


        

        const updatePayload = {};
        
        if (data.sku !== undefined) updatePayload.sku = data.sku;
        
        
        if (data.name !== undefined) updatePayload.name = data.name;
        
        
        if (data.description !== undefined) updatePayload.description = data.description;
        
        
        if (data.item_type !== undefined) updatePayload.item_type = data.item_type;
        
        
        if (data.uom !== undefined) updatePayload.uom = data.uom;
        
        
        if (data.is_lot_tracked !== undefined) updatePayload.is_lot_tracked = data.is_lot_tracked;
        
        
        if (data.requires_expiry !== undefined) updatePayload.requires_expiry = data.requires_expiry;
        
        
        if (data.shelf_life_days !== undefined) updatePayload.shelf_life_days = data.shelf_life_days;
        
        
        if (data.standard_cost !== undefined) updatePayload.standard_cost = data.standard_cost;
        
        
        if (data.standard_price !== undefined) updatePayload.standard_price = data.standard_price;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.company !== undefined) {
            await items.setCompany(
              
              data.company,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await items.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        

        
        await FileDBApi.replaceRelationFiles(
            {
                belongsTo: db.items.getTableName(),
                belongsToColumn: 'spec_documents',
                belongsToId: items.id,
            },
            data.spec_documents,
            options,
        );
        
        await FileDBApi.replaceRelationFiles(
            {
                belongsTo: db.items.getTableName(),
                belongsToColumn: 'images',
                belongsToId: items.id,
            },
            data.images,
            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.lots_item = await items.getLots_item({
            transaction
        });
        
        
        output.inventory_balances_item = await items.getInventory_balances_item({
            transaction
        });
        
        
        output.inventory_transactions_item = await items.getInventory_transactions_item({
            transaction
        });
        
        
        
        
        output.work_orders_item = await items.getWork_orders_item({
            transaction
        });
        
        
        
        output.material_issues_item = await items.getMaterial_issues_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.company = await items.getCompany({
            transaction
        });
        
        
        output.spec_documents = await items.getSpec_documents({
            transaction
        });
        
        
        output.images = await items.getImages({
            transaction
        });
        
        
        output.organizations = await items.getOrganizations({
            transaction
        });
        
        

        return output;
    }

    static async findAll(
          filter,
           globalAccess,  options
        ) {
        const limit = filter.limit || 0;
        let offset = 0;
        let where = {};
        const currentPage = +filter.page;

        
        const user = (options && options.currentUser) || null;
        const userOrganizations = (user && user.organizations?.id) || null;
        

        
        if (userOrganizations) {
            if (options?.currentUser?.organizationsId) {
                where.organizationsId = options.currentUser.organizationsId;
            }
        }
        

        offset = currentPage * limit;

        const orderBy = null;

    const transaction = (options && options.transaction) || undefined;

    let include = [

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

      {
        model: db.organizations,
        as: 'organizations',
        
      },



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

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

    ];

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

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

            
            

            
            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.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.standard_priceRange) {
                const [start, end] = filter.standard_priceRange;

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    standard_price: {
                    ...where.standard_price,
                            [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.is_lot_tracked) {
                where = {
                    ...where,
                is_lot_tracked: filter.is_lot_tracked,
            };
            }
            
            if (filter.requires_expiry) {
                where = {
                    ...where,
                requires_expiry: filter.requires_expiry,
            };
            }
            
            if (filter.status) {
                where = {
                    ...where,
                status: filter.status,
            };
            }
            


      

      
      if (filter.organizations) {
        const listItems = filter.organizations.split('|').map(item => {
          return  Utils.uuid(item)
        });

        where = {
          ...where,
          organizationsId: {[Op.or]: listItems}
        };
      }
      



            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,
                        },
                    };
                }
            }
        }
        

        
        if (globalAccess) {
            delete where.organizationsId;
        }
        

        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,  globalAccess, organizationId,) {
        let where = {};
        
        
        if (!globalAccess && organizationId) {
            where.organizationId = organizationId;
        }
        

        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,
        }));
    }

    
};

