# Daily Notification Plugin - Usage Guide

## Quick Start

```typescript
import { DailyNotification } from '@timesafari/daily-notification-plugin';

// 1. Configure the plugin
await DailyNotification.configure({
  storage: 'shared',           // Use shared SQLite database
  ttlSeconds: 1800,           // 30 minutes TTL
  prefetchLeadMinutes: 15     // Prefetch 15 minutes before delivery
});

// 2. Schedule a notification
await DailyNotification.scheduleDailyNotification({
  url: 'https://api.example.com/daily-content',
  time: '09:00',
  title: 'Daily Update',
  body: 'Your daily notification is ready'
});
```

## Configuration Options

### Storage Mode

- **`'shared'`** (Recommended): Uses shared SQLite database with WAL mode
- **`'tiered'`** (Legacy): Uses SharedPreferences/UserDefaults + in-memory cache

### TTL Settings

- **`ttlSeconds`**: Maximum age of content at delivery time (default: 1800 = 30 minutes)
- **`prefetchLeadMinutes`**: How early to prefetch content (default: 15 minutes)

### Performance Optimization

- **`enableETagSupport`**: Use conditional requests for bandwidth savings
- **`enableErrorHandling`**: Advanced retry logic with exponential backoff
- **`enablePerformanceOptimization`**: Database indexes, memory management, object pooling

## Static Daily Reminders

For simple daily reminders that don't require network content or content caching:

### Basic Usage

```typescript
// Schedule a simple daily reminder
await DailyNotification.scheduleDailyReminder({
  id: 'morning_checkin',
  title: 'Good Morning!',
  body: 'Time to check your TimeSafari community updates',
  time: '09:00'  // HH:mm format
});
```

### Advanced Configuration

```typescript
// Schedule a customized reminder
await DailyNotification.scheduleDailyReminder({
  id: 'evening_reflection',
  title: 'Evening Reflection',
  body: 'Take a moment to reflect on your day',
  time: '20:00',
  sound: true,
  vibration: true,
  priority: 'high',
  repeatDaily: true,
  timezone: 'America/New_York'
});
```

### Reminder Management

```typescript
// Get all scheduled reminders
const result = await DailyNotification.getScheduledReminders();
console.log('Scheduled reminders:', result.reminders);

// Update an existing reminder
await DailyNotification.updateDailyReminder('morning_checkin', {
  title: 'Updated Morning Check-in',
  time: '08:30',
  priority: 'high'
});

// Cancel a specific reminder
await DailyNotification.cancelDailyReminder('evening_reflection');
```

### Key Benefits

- ✅ **No Network Required**: Works completely offline
- ✅ **No Content Cache**: Direct notification display without caching
- ✅ **Simple API**: Easy-to-use methods for basic reminder functionality
- ✅ **Persistent**: Survives app restarts and device reboots
- ✅ **Cross-Platform**: Consistent behavior across Android, iOS, and Web

### Time Format

Use 24-hour format with leading zeros:
- ✅ Valid: `"09:00"`, `"12:30"`, `"23:59"`
- ❌ Invalid: `"9:00"`, `"24:00"`, `"12:60"`

## Platform-Specific Features

### Android

```typescript
// Check exact alarm status
const alarmStatus = await DailyNotification.getExactAlarmStatus();
if (!alarmStatus.canSchedule) {
  // Request permission or use windowed fallback
  await DailyNotification.requestExactAlarmPermission();
}

// Check reboot recovery status
const recoveryStatus = await DailyNotification.getRebootRecoveryStatus();
if (recoveryStatus.recoveryNeeded) {
  console.log('System may have rebooted - notifications restored');
}
```

### iOS

```typescript
// Background tasks are automatically handled
// The plugin uses BGTaskScheduler for T–lead prefetch
// No additional configuration needed
```

## Advanced Usage

### Error Handling

```typescript
// Configure retry behavior
await DailyNotification.configure({
  maxRetries: 3,
  baseRetryDelay: 1000,      // 1 second
  maxRetryDelay: 30000,      // 30 seconds
  backoffMultiplier: 2.0
});

// Monitor error metrics
const errorMetrics = await DailyNotification.getErrorMetrics();
console.log(`Network errors: ${errorMetrics.networkErrors}`);
console.log(`Cache hit ratio: ${errorMetrics.cacheHitRatio}`);
```

### Performance Monitoring

```typescript
// Get performance metrics
const metrics = await DailyNotification.getPerformanceMetrics();
console.log(`Performance score: ${metrics.overallScore}/100`);
console.log(`Memory usage: ${metrics.averageMemoryUsage}MB`);

// Optimize if needed
if (metrics.overallScore < 70) {
  await DailyNotification.optimizeMemory();
  await DailyNotification.optimizeDatabase();
}
```

### Rolling Window Management

```typescript
// Manual maintenance
await DailyNotification.maintainRollingWindow();

// Check status
const windowStats = await DailyNotification.getRollingWindowStats();
console.log(`Maintenance needed: ${windowStats.maintenanceNeeded}`);
console.log(`Time until next: ${windowStats.timeUntilNextMaintenance}ms`);
```

## Production Configuration

```typescript
// Recommended production settings
await DailyNotification.configure({
  storage: 'shared',
  ttlSeconds: 1800,
  prefetchLeadMinutes: 15,
  enableETagSupport: true,
  enableErrorHandling: true,
  enablePerformanceOptimization: true,
  memoryWarningThreshold: 50,    // MB
  memoryCriticalThreshold: 100,  // MB
  objectPoolSize: 20,
  maxObjectPoolSize: 100
});
```

## Troubleshooting

### Common Issues

1. **Notifications not firing**
   - Check exact alarm permissions on Android
   - Verify TTL settings aren't too restrictive
   - Ensure rolling window is maintained

2. **High memory usage**
   - Enable performance optimization
   - Check memory thresholds
   - Monitor object pool efficiency

3. **Network efficiency**
   - Enable ETag support
   - Monitor cache hit ratios
   - Check error retry patterns

### Debug Information

```typescript
// Get comprehensive debug info
const debugInfo = await DailyNotification.getDebugInfo();
console.log('Plugin Status:', debugInfo.status);
console.log('Configuration:', debugInfo.configuration);
console.log('Recent Errors:', debugInfo.recentErrors);
```

## Migration from Legacy Storage

```typescript
// The plugin automatically migrates from tiered to shared storage
// No manual migration needed - just configure with storage: 'shared'
await DailyNotification.configure({
  storage: 'shared'  // Triggers automatic migration
});
```

## Best Practices

1. **Always configure before scheduling** - Set up storage, TTL, and optimization features
2. **Monitor performance metrics** - Use built-in monitoring to optimize settings
3. **Handle errors gracefully** - Implement retry logic and fallback mechanisms
4. **Test on both platforms** - Android and iOS have different capabilities and limitations
5. **Use production settings** - Enable all optimization features for production use

## API Reference

See `src/definitions.ts` for complete TypeScript interface definitions.

## Examples

- **Basic Usage**: `examples/hello-poll.ts`
- **Stale Data UX**: `examples/stale-data-ux.ts`
- **Enterprise Features**: See `INTEGRATION_GUIDE.md` for enterprise integration patterns
