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

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

        const cycle_count_lines = await db.cycle_count_lines.create(
            {
                id: data.id || undefined,
        
        system_qty: data.system_qty
        ||
        null
            ,
            
        counted_qty: data.counted_qty
        ||
        null
            ,
            
        variance_qty: data.variance_qty
        ||
        null
            ,
            
        uom: data.uom
        ||
        null
            ,
            
        notes: data.notes
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await cycle_count_lines.setCycle_count( data.cycle_count || null, {
            transaction,
        });
        
        await cycle_count_lines.setLocation( data.location || null, {
            transaction,
        });
        
        await cycle_count_lines.setMaterial( data.material || null, {
            transaction,
        });
        
        await cycle_count_lines.setLot( data.lot || null, {
            transaction,
        });
        
        await cycle_count_lines.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

        

        return cycle_count_lines;
    }
    

    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 cycle_count_linesData = data.map((item, index) => ({
                id: item.id || undefined,
                
                system_qty: item.system_qty
            ||
            null
            ,
            
                counted_qty: item.counted_qty
            ||
            null
            ,
            
                variance_qty: item.variance_qty
            ||
            null
            ,
            
                uom: item.uom
            ||
            null
            ,
            
                notes: item.notes
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return cycle_count_lines;
    }

    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 cycle_count_lines = await db.cycle_count_lines.findByPk(id, {}, {transaction});


        

        const updatePayload = {};
        
        if (data.system_qty !== undefined) updatePayload.system_qty = data.system_qty;
        
        
        if (data.counted_qty !== undefined) updatePayload.counted_qty = data.counted_qty;
        
        
        if (data.variance_qty !== undefined) updatePayload.variance_qty = data.variance_qty;
        
        
        if (data.uom !== undefined) updatePayload.uom = data.uom;
        
        
        if (data.notes !== undefined) updatePayload.notes = data.notes;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.cycle_count !== undefined) {
            await cycle_count_lines.setCycle_count(
              
              data.cycle_count,
              
              { transaction }
            );
        }
        
        if (data.location !== undefined) {
            await cycle_count_lines.setLocation(
              
              data.location,
              
              { transaction }
            );
        }
        
        if (data.material !== undefined) {
            await cycle_count_lines.setMaterial(
              
              data.material,
              
              { transaction }
            );
        }
        
        if (data.lot !== undefined) {
            await cycle_count_lines.setLot(
              
              data.lot,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await cycle_count_lines.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        

        

        return cycle_count_lines;
    }

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

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

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


        return cycle_count_lines;
    }

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

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

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

        await cycle_count_lines.destroy({
            transaction
        });

        return cycle_count_lines;
    }

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

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

        if (!cycle_count_lines) {
            return cycle_count_lines;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.cycle_count = await cycle_count_lines.getCycle_count({
            transaction
        });
        
        
        output.location = await cycle_count_lines.getLocation({
            transaction
        });
        
        
        output.material = await cycle_count_lines.getMaterial({
            transaction
        });
        
        
        output.lot = await cycle_count_lines.getLot({
            transaction
        });
        
        
        output.organizations = await cycle_count_lines.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.cycle_counts,
        as: 'cycle_count',
        
        where: filter.cycle_count ? {
          [Op.or]: [
            { id: { [Op.in]: filter.cycle_count.split('|').map(term => Utils.uuid(term)) } },
            {
              count_number: {
                [Op.or]: filter.cycle_count.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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

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

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

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



    ];

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

            
            if (filter.uom) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'cycle_count_lines',
                        'uom',
                        filter.uom,
                    ),
                };
            }
            
            if (filter.notes) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'cycle_count_lines',
                        'notes',
                        filter.notes,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    variance_qty: {
                    ...where.variance_qty,
                            [Op.lte]: end,
                    },
                };
                }
            }
            

            if (filter.active !== undefined) {
                where = {
                    ...where,
                    active: filter.active === true || filter.active === 'true'
                };
            }

            


      

      

      

      

      
      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.cycle_count_lines.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(
                        'cycle_count_lines',
                        'uom',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

