
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
            ,
            
        tracking_mode: data.tracking_mode
        ||
        null
            ,
            
        is_active: data.is_active
        ||
        false
        
            ,
            
        sales_price: data.sales_price
        ||
        null
            ,
            
        purchase_cost: data.purchase_cost
        ||
        null
            ,
            
        reorder_point: data.reorder_point
        ||
        null
            ,
            
        reorder_qty: data.reorder_qty
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await items.setTenant( data.tenant || null, {
            transaction,
        });
        
        await items.setCategory( data.category || null, {
            transaction,
        });
        
        await items.setUom( data.uom || null, {
            transaction,
        });
        
        await items.setOrganizations( data.organizations || 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,
                
                sku: item.sku
            ||
            null
            ,
            
                name: item.name
            ||
            null
            ,
            
                description: item.description
            ||
            null
            ,
            
                item_type: item.item_type
            ||
            null
            ,
            
                tracking_mode: item.tracking_mode
            ||
            null
            ,
            
                is_active: item.is_active
            ||
            false
        
            ,
            
                sales_price: item.sales_price
            ||
            null
            ,
            
                purchase_cost: item.purchase_cost
            ||
            null
            ,
            
                reorder_point: item.reorder_point
            ||
            null
            ,
            
                reorder_qty: item.reorder_qty
            ||
            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 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.tracking_mode !== undefined) updatePayload.tracking_mode = data.tracking_mode;
        
        
        if (data.is_active !== undefined) updatePayload.is_active = data.is_active;
        
        
        if (data.sales_price !== undefined) updatePayload.sales_price = data.sales_price;
        
        
        if (data.purchase_cost !== undefined) updatePayload.purchase_cost = data.purchase_cost;
        
        
        if (data.reorder_point !== undefined) updatePayload.reorder_point = data.reorder_point;
        
        
        if (data.reorder_qty !== undefined) updatePayload.reorder_qty = data.reorder_qty;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.tenant !== undefined) {
            await items.setTenant(
              
              data.tenant,
              
              { transaction }
            );
        }
        
        if (data.category !== undefined) {
            await items.setCategory(
              
              data.category,
              
              { transaction }
            );
        }
        
        if (data.uom !== undefined) {
            await items.setUom(
              
              data.uom,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await items.setOrganizations(
              
              data.organizations,
              
              { 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.lots_item = await items.getLots_item({
            transaction
        });
        
        
        output.serial_numbers_item = await items.getSerial_numbers_item({
            transaction
        });
        
        
        
        output.inventory_transfer_lines_item = await items.getInventory_transfer_lines_item({
            transaction
        });
        
        
        output.stock_movements_item = await items.getStock_movements_item({
            transaction
        });
        
        
        
        output.quotation_lines_item = await items.getQuotation_lines_item({
            transaction
        });
        
        
        
        output.sales_order_lines_item = await items.getSales_order_lines_item({
            transaction
        });
        
        
        
        
        output.invoice_lines_item = await items.getInvoice_lines_item({
            transaction
        });
        
        
        
        output.customer_return_lines_item = await items.getCustomer_return_lines_item({
            transaction
        });
        
        
        
        output.purchase_order_lines_item = await items.getPurchase_order_lines_item({
            transaction
        });
        
        
        
        output.receipt_lines_item = await items.getReceipt_lines_item({
            transaction
        });
        
        
        
        output.vendor_bill_lines_item = await items.getVendor_bill_lines_item({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.tenant = await items.getTenant({
            transaction
        });
        
        
        output.category = await items.getCategory({
            transaction
        });
        
        
        output.uom = await items.getUom({
            transaction
        });
        
        
        output.images = await items.getImages({
            transaction
        });
        
        
        output.attachments = await items.getAttachments({
            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.tenants,
        as: 'tenant',
        
        where: filter.tenant ? {
          [Op.or]: [
            { id: { [Op.in]: filter.tenant.split('|').map(term => Utils.uuid(term)) } },
            {
              name: {
                [Op.or]: filter.tenant.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

      {
        model: db.item_categories,
        as: 'category',
        
        where: filter.category ? {
          [Op.or]: [
            { id: { [Op.in]: filter.category.split('|').map(term => Utils.uuid(term)) } },
            {
              name: {
                [Op.or]: filter.category.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)) } },
            {
              name: {
                [Op.or]: filter.uom.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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



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

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

    ];

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

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    sales_price: {
                    ...where.sales_price,
                            [Op.lte]: end,
                    },
                };
                }
            }
            
            if (filter.purchase_costRange) {
                const [start, end] = filter.purchase_costRange;

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    purchase_cost: {
                    ...where.purchase_cost,
                            [Op.lte]: end,
                    },
                };
                }
            }
            
            if (filter.reorder_pointRange) {
                const [start, end] = filter.reorder_pointRange;

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    reorder_point: {
                    ...where.reorder_point,
                            [Op.lte]: end,
                    },
                };
                }
            }
            
            if (filter.reorder_qtyRange) {
                const [start, end] = filter.reorder_qtyRange;

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    reorder_qty: {
                    ...where.reorder_qty,
                            [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_mode) {
                where = {
                    ...where,
                tracking_mode: filter.tracking_mode,
            };
            }
            
            if (filter.is_active) {
                where = {
                    ...where,
                is_active: filter.is_active,
            };
            }
            


      

      

      

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

    
};

