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

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

        const stock_receptions = await db.stock_receptions.create(
            {
                id: data.id || undefined,
        
        reception_number: data.reception_number
        ||
        null
            ,
            
        received_at: data.received_at
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        notes: data.notes
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await stock_receptions.setOrganization(currentUser.organization.id || null, {
            transaction,
        });
        
        await stock_receptions.setPurchase_order( data.purchase_order || null, {
            transaction,
        });
        
        await stock_receptions.setSupplier( data.supplier || null, {
            transaction,
        });
        
        await stock_receptions.setWarehouse( data.warehouse || null, {
            transaction,
        });
        

        

        
        await FileDBApi.replaceRelationFiles(
            {
                belongsTo: db.stock_receptions.getTableName(),
                belongsToColumn: 'attachment',
                belongsToId: stock_receptions.id,
            },
            data.attachment,
            options,
        );
        

        return stock_receptions;
    }
    

    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_receptionsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                reception_number: item.reception_number
            ||
            null
            ,
            
                received_at: item.received_at
            ||
            null
            ,
            
                status: item.status
            ||
            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_receptions = await db.stock_receptions.bulkCreate(stock_receptionsData, { transaction });

        // For each item created, replace relation files
        
        for (let i = 0; i < stock_receptions.length; i++) {
            await FileDBApi.replaceRelationFiles(
                {
                    belongsTo: db.stock_receptions.getTableName(),
                    belongsToColumn: 'attachment',
                    belongsToId: stock_receptions[i].id,
                },
                data[i].attachment,
                options,
            );
        }
        

        return stock_receptions;
    }

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


        

        const updatePayload = {};
        
        if (data.reception_number !== undefined) updatePayload.reception_number = data.reception_number;
        
        
        if (data.received_at !== undefined) updatePayload.received_at = data.received_at;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.notes !== undefined) updatePayload.notes = data.notes;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.organization !== undefined) {
            await stock_receptions.setOrganization(
              
              (globalAccess ? data.organization : currentUser.organization.id),
              
              { transaction }
            );
        }
        
        if (data.purchase_order !== undefined) {
            await stock_receptions.setPurchase_order(
              
              data.purchase_order,
              
              { transaction }
            );
        }
        
        if (data.supplier !== undefined) {
            await stock_receptions.setSupplier(
              
              data.supplier,
              
              { transaction }
            );
        }
        
        if (data.warehouse !== undefined) {
            await stock_receptions.setWarehouse(
              
              data.warehouse,
              
              { transaction }
            );
        }
        

        
        

        
        await FileDBApi.replaceRelationFiles(
            {
                belongsTo: db.stock_receptions.getTableName(),
                belongsToColumn: 'attachment',
                belongsToId: stock_receptions.id,
            },
            data.attachment,
            options,
        );
        

        return stock_receptions;
    }

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

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

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


        return stock_receptions;
    }

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

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

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

        await stock_receptions.destroy({
            transaction
        });

        return stock_receptions;
    }

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

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

        if (!stock_receptions) {
            return stock_receptions;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.stock_reception_items_stock_reception = await stock_receptions.getStock_reception_items_stock_reception({
            transaction
        });
        
        
        
        
        
        
        
        
        
        output.organization = await stock_receptions.getOrganization({
            transaction
        });
        
        
        output.purchase_order = await stock_receptions.getPurchase_order({
            transaction
        });
        
        
        output.supplier = await stock_receptions.getSupplier({
            transaction
        });
        
        
        output.warehouse = await stock_receptions.getWarehouse({
            transaction
        });
        
        
        output.attachment = await stock_receptions.getAttachment({
            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.organizations,
        as: 'organization',
        
      },

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

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



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

    ];

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

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

            
            

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

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

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

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

            
            if (filter.status) {
                where = {
                    ...where,
                status: filter.status,
            };
            }
            


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

        where = {
          ...where,
          organizationId: {[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_receptions.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_receptions',
                        'reception_number',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

