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

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

        const stock_adjustments = await db.stock_adjustments.create(
            {
                id: data.id || undefined,
        
        adjustment_number: data.adjustment_number
        ||
        null
            ,
            
        reason: data.reason
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        submitted_at: data.submitted_at
        ||
        null
            ,
            
        approved_at: data.approved_at
        ||
        null
            ,
            
        notes: data.notes
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await stock_adjustments.setBranch( data.branch || null, {
            transaction,
        });
        
        await stock_adjustments.setWarehouse( data.warehouse || null, {
            transaction,
        });
        
        await stock_adjustments.setRequested_by( data.requested_by || null, {
            transaction,
        });
        
        await stock_adjustments.setApproved_by( data.approved_by || null, {
            transaction,
        });
        
        await stock_adjustments.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

        

        return stock_adjustments;
    }
    

    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 stock_adjustmentsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                adjustment_number: item.adjustment_number
            ||
            null
            ,
            
                reason: item.reason
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
                submitted_at: item.submitted_at
            ||
            null
            ,
            
                approved_at: item.approved_at
            ||
            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 stock_adjustments = await db.stock_adjustments.bulkCreate(stock_adjustmentsData, { transaction });

        // For each item created, replace relation files
        

        return stock_adjustments;
    }

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


        

        const updatePayload = {};
        
        if (data.adjustment_number !== undefined) updatePayload.adjustment_number = data.adjustment_number;
        
        
        if (data.reason !== undefined) updatePayload.reason = data.reason;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.submitted_at !== undefined) updatePayload.submitted_at = data.submitted_at;
        
        
        if (data.approved_at !== undefined) updatePayload.approved_at = data.approved_at;
        
        
        if (data.notes !== undefined) updatePayload.notes = data.notes;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.branch !== undefined) {
            await stock_adjustments.setBranch(
              
              data.branch,
              
              { transaction }
            );
        }
        
        if (data.warehouse !== undefined) {
            await stock_adjustments.setWarehouse(
              
              data.warehouse,
              
              { transaction }
            );
        }
        
        if (data.requested_by !== undefined) {
            await stock_adjustments.setRequested_by(
              
              data.requested_by,
              
              { transaction }
            );
        }
        
        if (data.approved_by !== undefined) {
            await stock_adjustments.setApproved_by(
              
              data.approved_by,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await stock_adjustments.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        

        

        return stock_adjustments;
    }

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

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

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


        return stock_adjustments;
    }

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

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

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

        await stock_adjustments.destroy({
            transaction
        });

        return stock_adjustments;
    }

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

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

        if (!stock_adjustments) {
            return stock_adjustments;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.stock_adjustment_lines_stock_adjustment = await stock_adjustments.getStock_adjustment_lines_stock_adjustment({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.branch = await stock_adjustments.getBranch({
            transaction
        });
        
        
        output.warehouse = await stock_adjustments.getWarehouse({
            transaction
        });
        
        
        output.requested_by = await stock_adjustments.getRequested_by({
            transaction
        });
        
        
        output.approved_by = await stock_adjustments.getApproved_by({
            transaction
        });
        
        
        output.organizations = await stock_adjustments.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.branches,
        as: 'branch',
        
        where: filter.branch ? {
          [Op.or]: [
            { id: { [Op.in]: filter.branch.split('|').map(term => Utils.uuid(term)) } },
            {
              branch_name: {
                [Op.or]: filter.branch.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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

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

      {
        model: db.users,
        as: 'approved_by',
        
        where: filter.approved_by ? {
          [Op.or]: [
            { id: { [Op.in]: filter.approved_by.split('|').map(term => Utils.uuid(term)) } },
            {
              firstName: {
                [Op.or]: filter.approved_by.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.adjustment_number) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'stock_adjustments',
                        'adjustment_number',
                        filter.adjustment_number,
                    ),
                };
            }
            
            if (filter.notes) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'stock_adjustments',
                        'notes',
                        filter.notes,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

            
            if (filter.reason) {
                where = {
                    ...where,
                reason: filter.reason,
            };
            }
            
            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.stock_adjustments.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(
                        'stock_adjustments',
                        'adjustment_number',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

