# License Monitoring SDK

A comprehensive SDK for license management and remote monitoring with automatic system tracking, license validation, and remote control capabilities.

## Features

- **License Validation**: Automatic license key validation with distribution limits
- **System Tracking**: Automatic collection of system information and deployment details
- **Remote Control**: Database-driven remote command execution and application control
- **Data Logging**: Flexible API for logging user data operations
- **MongoDB Integration**: Built-in MongoDB connectivity for monitoring operations
- **Error Handling**: Comprehensive error handling and logging system

## Installation

```bash
npm install @ufdevsllc/authme2.0
```

## Quick Start

### Basic Usage

```javascript
import LicenseMonitoringSDK from '@ufdevsllc/authme2.0';

// Initialize the SDK
const sdk = new LicenseMonitoringSDK();

async function initializeApp() {
    try {
        // Initialize with your license key
        await sdk.init('your-license-key-here');
        
        console.log('SDK initialized successfully');
        
        // Your application code here
        
    } catch (error) {
        console.error('SDK initialization failed:', error.message);
        process.exit(1);
    }
}

initializeApp();
```

### Advanced Usage with Options

```javascript
import LicenseMonitoringSDK from '@ufdevsllc/authme2.0';

const sdk = new LicenseMonitoringSDK();

async function initializeApp() {
    try {
        await sdk.init('your-license-key-here', {
            validateLicense: true,           // Enable license validation (default: true)
            startSystemTracking: true,      // Enable system tracking (default: true)
            startRemoteControl: true,       // Enable remote control (default: true)
            exitOnLicenseFailure: true,     // Exit on license failure (default: true)
            logToConsole: true              // Log to console (default: true)
        });
        
        console.log('SDK initialized with custom options');
        
    } catch (error) {
        console.error('Initialization failed:', error.message);
    }
}
```

## API Reference

### Initialization

#### `sdk.init(licenseKey, options)`

Initialize the SDK with a license key and optional configuration.

**Parameters:**
- `licenseKey` (string): Your license key (required)
- `options` (object): Configuration options (optional)

**Options:**
- `validateLicense` (boolean): Enable license validation (default: true)
- `startSystemTracking` (boolean): Enable automatic system tracking (default: true)
- `startRemoteControl` (boolean): Enable remote control capabilities (default: true)
- `exitOnLicenseFailure` (boolean): Exit process on license validation failure (default: true)
- `logToConsole` (boolean): Enable console logging (default: true)

### Data Logging

#### `sdk.logData(collection, data, operation)`

Log data operations to the monitoring database.

```javascript
// Log user data
await sdk.logData('users', { 
    name: 'John Doe', 
    email: 'john@example.com' 
}, 'create');

// Log custom operations
await sdk.logData('orders', { 
    orderId: '12345', 
    amount: 99.99 
}, 'purchase');
```

#### `sdk.logUserActivity(userId, action, details)`

Log user activity with additional details.

```javascript
await sdk.logUserActivity('user123', 'login', {
    ip: '192.168.1.1',
    userAgent: 'Mozilla/5.0...',
    timestamp: new Date()
});
```

#### `sdk.logModelOperation(modelName, operation, data)`

Log model-specific operations.

```javascript
await sdk.logModelOperation('User', 'update', {
    userId: 'user123',
    changes: { email: 'newemail@example.com' }
});
```

### License Management

#### `sdk.isLicenseValid()`

Check if the current license is valid.

```javascript
const isValid = await sdk.isLicenseValid();
if (!isValid) {
    console.log('License is invalid or expired');
}
```

#### `sdk.getLicenseStatus()`

Get detailed license status information.

```javascript
const status = await sdk.getLicenseStatus();
console.log('License status:', status);
```

### Application Control

#### `sdk.isApplicationBlocked()`

Check if the application is blocked by remote control.

```javascript
if (sdk.isApplicationBlocked()) {
    console.log('Application is blocked:', sdk.getBlockReason());
}
```

### Health Monitoring

#### `sdk.getStatus()`

Get current SDK status and component health.

```javascript
const status = sdk.getStatus();
console.log('SDK Status:', status);
```

#### `sdk.healthCheck()`

Perform a comprehensive health check on all components.

```javascript
const health = await sdk.healthCheck();
console.log('Health Check:', health);
```

### Cleanup

#### `sdk.shutdown()`

Properly shutdown the SDK and clean up resources.

```javascript
// Graceful shutdown
process.on('SIGINT', async () => {
    console.log('Shutting down...');
    await sdk.shutdown();
    process.exit(0);
});
```

## Integration Examples

### Express.js Integration

```javascript
import express from 'express';
import LicenseMonitoringSDK from '@ufdevsllc/authme2.0';

const app = express();
const sdk = new LicenseMonitoringSDK();

// Initialize SDK before starting server
async function startServer() {
    try {
        await sdk.init('your-license-key-here');
        
        // Middleware to check if application is blocked
        app.use((req, res, next) => {
            if (sdk.isApplicationBlocked()) {
                return res.status(503).json({
                    error: 'Service temporarily unavailable',
                    reason: sdk.getBlockReason()
                });
            }
            next();
        });
        
        // Log user activities
        app.post('/api/users', async (req, res) => {
            try {
                // Your user creation logic
                const user = await createUser(req.body);
                
                // Log the operation
                await sdk.logData('users', user, 'create');
                
                res.json(user);
            } catch (error) {
                res.status(500).json({ error: error.message });
            }
        });
        
        app.listen(3000, () => {
            console.log('Server running on port 3000');
        });
        
    } catch (error) {
        console.error('Failed to start server:', error.message);
        process.exit(1);
    }
}

startServer();
```

### Mongoose Integration

```javascript
import mongoose from 'mongoose';
import LicenseMonitoringSDK from '@ufdevsllc/authme2.0';

const sdk = new LicenseMonitoringSDK();

// User schema
const userSchema = new mongoose.Schema({
    name: String,
    email: String
});

// Post-save hook to log operations
userSchema.post('save', async function(doc) {
    try {
        await sdk.logModelOperation('User', 'save', {
            userId: doc._id,
            data: doc.toObject()
        });
    } catch (error) {
        console.error('Failed to log user save:', error.message);
    }
});

const User = mongoose.model('User', userSchema);

// Initialize SDK and connect to your database
async function initialize() {
    try {
        await sdk.init('your-license-key-here');
        await mongoose.connect('your-mongodb-connection-string');
        console.log('Application initialized successfully');
    } catch (error) {
        console.error('Initialization failed:', error.message);
        process.exit(1);
    }
}

initialize();
```

## Error Handling

The SDK includes comprehensive error handling. All methods that can fail will throw errors that should be caught:

```javascript
try {
    await sdk.init('invalid-license-key');
} catch (error) {
    if (error.message.includes('License validation failed')) {
        console.error('Invalid license key provided');
        // Handle license error
    } else if (error.message.includes('Database initialization failed')) {
        console.error('Database connection error');
        // Handle database error
    } else {
        console.error('Unknown initialization error:', error.message);
    }
}
```

## Requirements

- Node.js >= 14.0.0
- MongoDB connection (handled automatically by the SDK)
- Valid license key

## Dependencies

- `mongoose`: MongoDB object modeling
- `os`: Operating system utilities (built-in Node.js module)

## License

ISC

## Documentation

### 📚 Complete Documentation Suite

- **[CLIENT-DOCUMENTATION.md](./CLIENT-DOCUMENTATION.md)** - Complete guide for developers integrating the SDK
- **[VENDOR-DOCUMENTATION.md](./VENDOR-DOCUMENTATION.md)** - Comprehensive guide for software vendors managing licenses
- **[API-REFERENCE.md](./API-REFERENCE.md)** - Complete API reference with all classes and methods
- **[FEATURES-OVERVIEW.md](./FEATURES-OVERVIEW.md)** - Detailed overview of all SDK features and capabilities

### 🚀 Quick Links

- **Getting Started**: See [CLIENT-DOCUMENTATION.md](./CLIENT-DOCUMENTATION.md#quick-start-guide)
- **License Management**: See [VENDOR-DOCUMENTATION.md](./VENDOR-DOCUMENTATION.md#license-creation-and-management)
- **Integration Examples**: See [CLIENT-DOCUMENTATION.md](./CLIENT-DOCUMENTATION.md#framework-integrations)
- **API Methods**: See [API-REFERENCE.md](./API-REFERENCE.md#main-sdk-class)
- **All Features**: See [FEATURES-OVERVIEW.md](./FEATURES-OVERVIEW.md#core-features)

### 📖 Documentation by Role

**For Developers/Clients:**
- Start with [CLIENT-DOCUMENTATION.md](./CLIENT-DOCUMENTATION.md) for integration guide
- Reference [API-REFERENCE.md](./API-REFERENCE.md) for technical details
- Check [FEATURES-OVERVIEW.md](./FEATURES-OVERVIEW.md) for feature explanations

**For Software Vendors:**
- Start with [VENDOR-DOCUMENTATION.md](./VENDOR-DOCUMENTATION.md) for license management
- Reference [FEATURES-OVERVIEW.md](./FEATURES-OVERVIEW.md) for monitoring capabilities
- Use [API-REFERENCE.md](./API-REFERENCE.md) for technical implementation

## Real-World Testing

The SDK has been thoroughly tested with real applications. See the `real-world-test/` directory for:

- **[USAGE-GUIDE.md](./real-world-test/USAGE-GUIDE.md)** - Complete usage examples with database output
- **[FINAL-SUMMARY.md](./real-world-test/FINAL-SUMMARY.md)** - Implementation summary and verification
- **[TEST_RESULTS.md](./real-world-test/TEST_RESULTS.md)** - Comprehensive test results
- **Demo Scripts** - Working examples you can run immediately

## Support

### 📞 Support Channels

- **Issues**: https://github.com/ufdevsllc/authme2.0/issues
- **Documentation**: Complete guides in this repository
- **Email**: support@ufdevsllc.com

### 🆘 Getting Help

1. **Check Documentation**: Start with the relevant documentation file above
2. **Run Examples**: Try the examples in `real-world-test/` directory
3. **Search Issues**: Check existing GitHub issues
4. **Create Issue**: Open a new issue with details and error messages

## Author

ufdevs llc @rameshvishwakarma