import { Server as SocketServer, Socket } from 'socket.io';
import { createTransport, Transporter } from 'nodemailer';
import { auditLogger } from '../workflow/auditLogger';
import { rbacService } from '../api/services/rbac.service';
import { getAuthenticatedClient } from '../../scripts/utils/directus-client';
import Bull from 'bull';
import Redis from 'redis';

// Import Directus SDK functions
const directusSdk = require('@directus/sdk');
const readItem = directusSdk.readItem as any;
const readItems = directusSdk.readItems as any;
const createItem = directusSdk.createItem as any;
const updateItem = directusSdk.updateItem as any;

/**
 * Notification Types
 */
export enum NotificationType {
  TASK_ASSIGNED = 'task_assigned',
  TASK_UPDATED = 'task_updated',
  TASK_COMPLETED = 'task_completed',
  TASK_OVERDUE = 'task_overdue',
  COMMENT_ADDED = 'comment_added',
  MENTION = 'mention',
  STATUS_CHANGED = 'status_changed',
  DEADLINE_APPROACHING = 'deadline_approaching',
  WORKFLOW_TRIGGERED = 'workflow_triggered',
  COLLABORATION_INVITE = 'collaboration_invite'
}

/**
 * Notification Priority Levels
 */
export enum NotificationPriority {
  LOW = 'low',
  MEDIUM = 'medium',
  HIGH = 'high',
  URGENT = 'urgent'
}

/**
 * Notification Interface
 */
export interface Notification {
  id?: string;
  type: NotificationType;
  priority: NotificationPriority;
  userId: string;
  title: string;
  message: string;
  metadata?: Record<string, any>;
  read: boolean;
  readAt?: string;
  createdAt: string;
  expiresAt?: string;
  actionUrl?: string;
  actions?: NotificationAction[];
}

/**
 * Notification Action
 */
export interface NotificationAction {
  label: string;
  action: string;
  url?: string;
  data?: Record<string, any>;
}

/**
 * User Notification Preferences
 */
export interface NotificationPreferences {
  userId: string;
  email: {
    enabled: boolean;
    frequency: 'instant' | 'hourly' | 'daily' | 'weekly';
    types: NotificationType[];
  };
  realtime: {
    enabled: boolean;
    types: NotificationType[];
    sound: boolean;
    desktop: boolean;
  };
  doNotDisturb: {
    enabled: boolean;
    startTime?: string; // HH:MM format
    endTime?: string;   // HH:MM format
    timezone?: string;
  };
}

/**
 * Email Template Data
 */
interface EmailTemplateData {
  userName: string;
  title: string;
  message: string;
  actionUrl?: string;
  actionLabel?: string;
  priority: string;
  metadata?: Record<string, any>;
}

/**
 * Notification Service
 * Manages real-time and email notifications
 */
export class NotificationService {
  private io: SocketServer | null = null;
  private emailTransporter: Transporter | null = null;
  private directusClient: any;
  private emailQueue: Bull.Queue | null = null;
  private connectedUsers: Map<string, Set<string>> = new Map(); // userId -> Set of socketIds
  private userPreferences: Map<string, NotificationPreferences> = new Map();
  private redisClient: any;

  constructor() {
    this.initializeServices();
  }

  /**
   * Initialize all services
   */
  private async initializeServices() {
    // Initialize Directus client
    this.directusClient = await getAuthenticatedClient();

    // Initialize Redis client
    this.redisClient = Redis.createClient({
      socket: {
        host: process.env.REDIS_HOST || 'localhost',
        port: parseInt(process.env.REDIS_PORT || '6379')
      }
    });

    await this.redisClient.connect();

    // Initialize email queue
    this.emailQueue = new Bull('email-notifications', {
      redis: {
        host: process.env.REDIS_HOST || 'localhost',
        port: parseInt(process.env.REDIS_PORT || '6379')
      }
    });

    // Process email queue
    this.emailQueue.process(async (job) => {
      return this.processEmailJob(job.data);
    });

    // Initialize email transporter
    this.initializeEmailTransporter();

    // Load user preferences
    await this.loadUserPreferences();
  }

  /**
   * Initialize Socket.io server
   */
  initializeSocketServer(io: SocketServer) {
    this.io = io;

    // Set up Socket.io middleware for authentication
    this.io.use(async (socket: Socket, next) => {
      try {
        const token = socket.handshake.auth.token;
        if (!token) {
          return next(new Error('Authentication token required'));
        }

        // Verify token and get user
        const userId = await rbacService.verifyToken(token);
        if (!userId) {
          return next(new Error('Invalid authentication token'));
        }

        // Attach user info to socket
        (socket as any).userId = userId;
        next();
      } catch (error) {
        next(new Error('Authentication failed'));
      }
    });

    // Handle connections
    this.io.on('connection', (socket: Socket) => {
      const userId = (socket as any).userId;
      console.log(`User ${userId} connected via socket ${socket.id}`);

      // Track connected user
      this.addConnectedUser(userId, socket.id);

      // Join user-specific room
      socket.join(`user:${userId}`);

      // Send pending notifications
      this.sendPendingNotifications(userId);

      // Handle notification events
      socket.on('notification:markRead', async (notificationId: string) => {
        await this.markNotificationAsRead(notificationId, userId);
      });

      socket.on('notification:markAllRead', async () => {
        await this.markAllNotificationsAsRead(userId);
      });

      socket.on('notification:updatePreferences', async (preferences: Partial<NotificationPreferences>) => {
        await this.updateUserPreferences(userId, preferences);
      });

      socket.on('notification:subscribe', async (types: NotificationType[]) => {
        await this.subscribeToNotificationTypes(userId, types);
      });

      socket.on('notification:unsubscribe', async (types: NotificationType[]) => {
        await this.unsubscribeFromNotificationTypes(userId, types);
      });

      // Handle disconnection
      socket.on('disconnect', () => {
        console.log(`User ${userId} disconnected from socket ${socket.id}`);
        this.removeConnectedUser(userId, socket.id);
      });
    });
  }

  /**
   * Initialize email transporter
   */
  private initializeEmailTransporter() {
    const emailConfig = {
      host: process.env.SMTP_HOST || 'smtp.gmail.com',
      port: parseInt(process.env.SMTP_PORT || '587'),
      secure: process.env.SMTP_SECURE === 'true',
      auth: {
        user: process.env.SMTP_USER,
        pass: process.env.SMTP_PASS
      }
    };

    if (emailConfig.auth.user && emailConfig.auth.pass) {
      this.emailTransporter = createTransport(emailConfig);
      console.log('Email transporter initialized');
    } else {
      console.warn('Email configuration not provided, email notifications disabled');
    }
  }

  /**
   * Send notification to user(s)
   */
  async sendNotification(
    userIds: string | string[],
    notification: Omit<Notification, 'id' | 'userId' | 'createdAt' | 'read' | 'readAt'>
  ): Promise<void> {
    const users = Array.isArray(userIds) ? userIds : [userIds];
    const timestamp = new Date().toISOString();

    for (const userId of users) {
      try {
        // Create notification record
        const notificationData: Notification = {
          ...notification,
          userId,
          read: false,
          createdAt: timestamp
        };

        // Save to database
        const savedNotification = await this.saveNotification(notificationData);

        // Check user preferences
        const preferences = await this.getUserPreferences(userId);

        // Send real-time notification if enabled and user is online
        if (preferences.realtime.enabled && this.shouldSendRealtimeNotification(notification.type, preferences)) {
          await this.sendRealtimeNotification(userId, savedNotification);
        }

        // Queue email notification if enabled
        if (preferences.email.enabled && this.shouldSendEmailNotification(notification.type, preferences)) {
          await this.queueEmailNotification(userId, savedNotification, preferences.email.frequency);
        }

        // Log notification
        await auditLogger.log({
          action: 'notification_sent',
          entity_type: 'system',
          entity_id: savedNotification.id!,
          actor_type: 'system',
          severity: 'info'
        });
      } catch (error) {
        console.error(`Failed to send notification to user ${userId}:`, error);
      }
    }
  }

  /**
   * Send real-time notification via Socket.io
   */
  private async sendRealtimeNotification(userId: string, notification: Notification): Promise<void> {
    if (!this.io) return;

    // Check if user is in DND mode
    if (await this.isUserInDND(userId)) {
      console.log(`User ${userId} is in DND mode, skipping real-time notification`);
      return;
    }

    // Emit to user's room
    this.io.to(`user:${userId}`).emit('notification:new', notification);

    // Emit to specific sockets if user has multiple connections
    const socketIds = this.connectedUsers.get(userId);
    if (socketIds && socketIds.size > 0) {
      socketIds.forEach(socketId => {
        this.io!.to(socketId).emit('notification:new', notification);
      });
    }
  }

  /**
   * Queue email notification
   */
  private async queueEmailNotification(
    userId: string,
    notification: Notification,
    frequency: 'instant' | 'hourly' | 'daily' | 'weekly'
  ): Promise<void> {
    if (!this.emailQueue) return;

    const delay = this.getEmailDelay(frequency);

    await this.emailQueue.add(
      {
        userId,
        notification,
        frequency
      },
      {
        delay,
        attempts: 3,
        backoff: {
          type: 'exponential',
          delay: 5000
        }
      }
    );
  }

  /**
   * Process email job from queue
   */
  private async processEmailJob(jobData: any): Promise<void> {
    const { userId, notification, frequency } = jobData;

    if (frequency === 'instant') {
      // Send single notification immediately
      await this.sendEmailNotification(userId, notification);
    } else {
      // Batch notifications for digest
      await this.sendEmailDigest(userId, frequency);
    }
  }

  /**
   * Send single email notification
   */
  private async sendEmailNotification(userId: string, notification: Notification): Promise<void> {
    if (!this.emailTransporter) return;

    try {
      // Get user details
      const user = await this.directusClient.request(
        readItem('directus_users', userId, {
          fields: ['email', 'first_name', 'last_name']
        })
      );

      if (!user.email) return;

      // Prepare email template data
      const templateData: EmailTemplateData = {
        userName: `${user.first_name} ${user.last_name}`.trim() || user.email,
        title: notification.title,
        message: notification.message,
        actionUrl: notification.actionUrl,
        actionLabel: notification.actions?.[0]?.label || 'View Details',
        priority: notification.priority,
        metadata: notification.metadata
      };

      // Generate email HTML
      const html = this.generateEmailHTML(templateData);

      // Send email
      await this.emailTransporter.sendMail({
        from: process.env.SMTP_FROM || 'noreply@taskmanagement.com',
        to: user.email,
        subject: `[${notification.priority.toUpperCase()}] ${notification.title}`,
        html
      });

      console.log(`Email notification sent to ${user.email}`);
    } catch (error) {
      console.error(`Failed to send email notification:`, error);
      throw error;
    }
  }

  /**
   * Send email digest
   */
  private async sendEmailDigest(userId: string, frequency: 'hourly' | 'daily' | 'weekly'): Promise<void> {
    if (!this.emailTransporter) return;

    try {
      // Get unread notifications for digest
      const notifications = await this.getUnreadNotifications(userId, frequency);
      
      if (notifications.length === 0) return;

      // Get user details
      const user = await this.directusClient.request(
        readItem('directus_users', userId, {
          fields: ['email', 'first_name', 'last_name']
        })
      );

      if (!user.email) return;

      // Generate digest HTML
      const html = this.generateDigestHTML({
        userName: `${user.first_name} ${user.last_name}`.trim() || user.email,
        notifications,
        frequency
      });

      // Send digest email
      await this.emailTransporter.sendMail({
        from: process.env.SMTP_FROM || 'noreply@taskmanagement.com',
        to: user.email,
        subject: `Your ${frequency} notification digest - ${notifications.length} updates`,
        html
      });

      // Mark notifications as emailed
      await this.markNotificationsAsEmailed(notifications.map(n => n.id!));

      console.log(`Email digest sent to ${user.email} with ${notifications.length} notifications`);
    } catch (error) {
      console.error(`Failed to send email digest:`, error);
      throw error;
    }
  }

  /**
   * Generate email HTML template
   */
  private generateEmailHTML(data: EmailTemplateData): string {
    return `
      <!DOCTYPE html>
      <html>
      <head>
        <style>
          body { font-family: Arial, sans-serif; line-height: 1.6; color: #333; }
          .container { max-width: 600px; margin: 0 auto; padding: 20px; }
          .header { background: #007bff; color: white; padding: 20px; text-align: center; }
          .priority-urgent { border-left: 5px solid #dc3545; }
          .priority-high { border-left: 5px solid #ffc107; }
          .priority-medium { border-left: 5px solid #17a2b8; }
          .priority-low { border-left: 5px solid #6c757d; }
          .content { padding: 20px; background: #f8f9fa; margin: 20px 0; }
          .button { display: inline-block; padding: 10px 20px; background: #007bff; color: white; text-decoration: none; border-radius: 5px; }
          .footer { text-align: center; padding: 20px; color: #6c757d; font-size: 12px; }
        </style>
      </head>
      <body>
        <div class="container">
          <div class="header">
            <h1>Task Management Notification</h1>
          </div>
          <div class="content priority-${data.priority}">
            <h2>Hi ${data.userName},</h2>
            <h3>${data.title}</h3>
            <p>${data.message}</p>
            ${data.actionUrl ? `
              <p style="text-align: center; margin-top: 30px;">
                <a href="${data.actionUrl}" class="button">${data.actionLabel}</a>
              </p>
            ` : ''}
          </div>
          <div class="footer">
            <p>You received this notification because of your subscription preferences.</p>
            <p><a href="${process.env.APP_URL}/preferences">Manage Preferences</a></p>
          </div>
        </div>
      </body>
      </html>
    `;
  }

  /**
   * Generate digest email HTML
   */
  private generateDigestHTML(data: {
    userName: string;
    notifications: Notification[];
    frequency: string;
  }): string {
    const notificationItems = data.notifications.map(n => `
      <div style="border-left: 3px solid ${this.getPriorityColor(n.priority)}; padding: 10px; margin: 10px 0; background: white;">
        <strong>${n.title}</strong>
        <p style="color: #666; margin: 5px 0;">${n.message}</p>
        <small style="color: #999;">${new Date(n.createdAt).toLocaleString()}</small>
      </div>
    `).join('');

    return `
      <!DOCTYPE html>
      <html>
      <head>
        <style>
          body { font-family: Arial, sans-serif; line-height: 1.6; color: #333; }
          .container { max-width: 600px; margin: 0 auto; padding: 20px; }
          .header { background: #007bff; color: white; padding: 20px; text-align: center; }
          .content { padding: 20px; background: #f8f9fa; }
          .footer { text-align: center; padding: 20px; color: #6c757d; font-size: 12px; }
        </style>
      </head>
      <body>
        <div class="container">
          <div class="header">
            <h1>Your ${data.frequency} Notification Digest</h1>
          </div>
          <div class="content">
            <h2>Hi ${data.userName},</h2>
            <p>You have ${data.notifications.length} new notifications:</p>
            ${notificationItems}
          </div>
          <div class="footer">
            <p><a href="${process.env.APP_URL}/notifications">View All Notifications</a></p>
            <p><a href="${process.env.APP_URL}/preferences">Manage Preferences</a></p>
          </div>
        </div>
      </body>
      </html>
    `;
  }

  /**
   * Helper: Get priority color
   */
  private getPriorityColor(priority: NotificationPriority): string {
    switch (priority) {
      case NotificationPriority.URGENT: return '#dc3545';
      case NotificationPriority.HIGH: return '#ffc107';
      case NotificationPriority.MEDIUM: return '#17a2b8';
      case NotificationPriority.LOW: return '#6c757d';
      default: return '#6c757d';
    }
  }

  /**
   * Helper: Get email delay based on frequency
   */
  private getEmailDelay(frequency: string): number {
    switch (frequency) {
      case 'instant': return 0;
      case 'hourly': return 60 * 60 * 1000;
      case 'daily': return 24 * 60 * 60 * 1000;
      case 'weekly': return 7 * 24 * 60 * 60 * 1000;
      default: return 0;
    }
  }

  /**
   * Save notification to database
   */
  private async saveNotification(notification: Notification): Promise<Notification> {
    if (!this.directusClient) await this.initializeServices();

    const saved = await this.directusClient.request(
      createItem('notifications', notification)
    );

    return { ...notification, id: saved.id };
  }

  /**
   * Get user notification preferences
   */
  private async getUserPreferences(userId: string): Promise<NotificationPreferences> {
    // Check cache first
    if (this.userPreferences.has(userId)) {
      return this.userPreferences.get(userId)!;
    }

    // Load from database
    try {
      const prefs = await this.directusClient.request(
        readItem('notification_preferences', userId)
      );

      const preferences: NotificationPreferences = {
        userId,
        email: prefs.email || {
          enabled: true,
          frequency: 'instant',
          types: Object.values(NotificationType)
        },
        realtime: prefs.realtime || {
          enabled: true,
          types: Object.values(NotificationType),
          sound: true,
          desktop: true
        },
        doNotDisturb: prefs.doNotDisturb || {
          enabled: false
        }
      };

      this.userPreferences.set(userId, preferences);
      return preferences;
    } catch (error) {
      // Return default preferences if not found
      const defaultPrefs: NotificationPreferences = {
        userId,
        email: {
          enabled: true,
          frequency: 'instant',
          types: Object.values(NotificationType)
        },
        realtime: {
          enabled: true,
          types: Object.values(NotificationType),
          sound: true,
          desktop: true
        },
        doNotDisturb: {
          enabled: false
        }
      };

      this.userPreferences.set(userId, defaultPrefs);
      return defaultPrefs;
    }
  }

  /**
   * Update user notification preferences
   */
  async updateUserPreferences(userId: string, preferences: Partial<NotificationPreferences>): Promise<void> {
    const current = await this.getUserPreferences(userId);
    const updated = { ...current, ...preferences };

    // Save to database
    await this.directusClient.request(
      updateItem('notification_preferences', userId, updated)
    );

    // Update cache
    this.userPreferences.set(userId, updated);

    // Notify user of preference update
    if (this.io) {
      this.io.to(`user:${userId}`).emit('preferences:updated', updated);
    }
  }

  /**
   * Load all user preferences
   */
  private async loadUserPreferences(): Promise<void> {
    try {
      const preferences = await this.directusClient.request(
        readItems('notification_preferences')
      );

      preferences.forEach((pref: any) => {
        this.userPreferences.set(pref.userId, pref);
      });

      console.log(`Loaded preferences for ${preferences.length} users`);
    } catch (error) {
      console.error('Failed to load user preferences:', error);
    }
  }

  /**
   * Check if notification type should be sent real-time
   */
  private shouldSendRealtimeNotification(type: NotificationType, preferences: NotificationPreferences): boolean {
    return preferences.realtime.types.includes(type);
  }

  /**
   * Check if notification type should be sent via email
   */
  private shouldSendEmailNotification(type: NotificationType, preferences: NotificationPreferences): boolean {
    return preferences.email.types.includes(type);
  }

  /**
   * Check if user is in Do Not Disturb mode
   */
  private async isUserInDND(userId: string): Promise<boolean> {
    const preferences = await this.getUserPreferences(userId);
    
    if (!preferences.doNotDisturb.enabled) return false;

    const { startTime, endTime, timezone = 'UTC' } = preferences.doNotDisturb;
    if (!startTime || !endTime) return false;

    // Check current time against DND schedule
    const now = new Date();
    const userTime = new Date(now.toLocaleString('en-US', { timeZone: timezone }));
    const currentTime = userTime.getHours() * 60 + userTime.getMinutes();

    const [startHour, startMin] = startTime.split(':').map(Number);
    const [endHour, endMin] = endTime.split(':').map(Number);
    const dndStart = startHour * 60 + startMin;
    const dndEnd = endHour * 60 + endMin;

    if (dndStart <= dndEnd) {
      return currentTime >= dndStart && currentTime <= dndEnd;
    } else {
      // DND spans midnight
      return currentTime >= dndStart || currentTime <= dndEnd;
    }
  }

  /**
   * Track connected user
   */
  private addConnectedUser(userId: string, socketId: string): void {
    if (!this.connectedUsers.has(userId)) {
      this.connectedUsers.set(userId, new Set());
    }
    this.connectedUsers.get(userId)!.add(socketId);
  }

  /**
   * Remove connected user
   */
  private removeConnectedUser(userId: string, socketId: string): void {
    const sockets = this.connectedUsers.get(userId);
    if (sockets) {
      sockets.delete(socketId);
      if (sockets.size === 0) {
        this.connectedUsers.delete(userId);
      }
    }
  }

  /**
   * Send pending notifications to newly connected user
   */
  private async sendPendingNotifications(userId: string): Promise<void> {
    try {
      const notifications = await this.directusClient.request(
        readItems('notifications', {
          filter: {
            userId: { _eq: userId },
            read: { _eq: false }
          },
          sort: ['-createdAt'],
          limit: 20
        })
      );

      if (notifications.length > 0 && this.io) {
        this.io.to(`user:${userId}`).emit('notifications:pending', notifications);
      }
    } catch (error) {
      console.error(`Failed to send pending notifications to user ${userId}:`, error);
    }
  }

  /**
   * Mark notification as read
   */
  async markNotificationAsRead(notificationId: string, userId: string): Promise<void> {
    try {
      await this.directusClient.request(
        updateItem('notifications', notificationId, {
          read: true,
          readAt: new Date().toISOString()
        })
      );

      // Notify all user's connections
      if (this.io) {
        this.io.to(`user:${userId}`).emit('notification:read', notificationId);
      }
    } catch (error) {
      console.error(`Failed to mark notification ${notificationId} as read:`, error);
    }
  }

  /**
   * Mark all notifications as read for a user
   */
  async markAllNotificationsAsRead(userId: string): Promise<void> {
    try {
      // Get all unread notifications
      const unreadNotifications = await this.directusClient.request(
        readItems('notifications', {
          filter: {
            userId: { _eq: userId },
            read: { _eq: false }
          },
          fields: ['id']
        })
      );

      // Update all to read
      const timestamp = new Date().toISOString();
      for (const notification of unreadNotifications) {
        await this.directusClient.request(
          updateItem('notifications', notification.id, {
            read: true,
            readAt: timestamp
          })
        );
      }

      // Notify all user's connections
      if (this.io) {
        this.io.to(`user:${userId}`).emit('notifications:allRead');
      }
    } catch (error) {
      console.error(`Failed to mark all notifications as read for user ${userId}:`, error);
    }
  }

  /**
   * Subscribe to notification types
   */
  async subscribeToNotificationTypes(userId: string, types: NotificationType[]): Promise<void> {
    const preferences = await this.getUserPreferences(userId);
    
    // Add types to both email and realtime
    const emailTypes = new Set([...preferences.email.types, ...types]);
    const realtimeTypes = new Set([...preferences.realtime.types, ...types]);

    await this.updateUserPreferences(userId, {
      email: { ...preferences.email, types: Array.from(emailTypes) },
      realtime: { ...preferences.realtime, types: Array.from(realtimeTypes) }
    });
  }

  /**
   * Unsubscribe from notification types
   */
  async unsubscribeFromNotificationTypes(userId: string, types: NotificationType[]): Promise<void> {
    const preferences = await this.getUserPreferences(userId);
    
    // Remove types from both email and realtime
    const emailTypes = preferences.email.types.filter(t => !types.includes(t));
    const realtimeTypes = preferences.realtime.types.filter(t => !types.includes(t));

    await this.updateUserPreferences(userId, {
      email: { ...preferences.email, types: emailTypes },
      realtime: { ...preferences.realtime, types: realtimeTypes }
    });
  }

  /**
   * Get unread notifications for digest
   */
  private async getUnreadNotifications(userId: string, frequency: string): Promise<Notification[]> {
    const cutoffTime = new Date();
    
    switch (frequency) {
      case 'hourly':
        cutoffTime.setHours(cutoffTime.getHours() - 1);
        break;
      case 'daily':
        cutoffTime.setDate(cutoffTime.getDate() - 1);
        break;
      case 'weekly':
        cutoffTime.setDate(cutoffTime.getDate() - 7);
        break;
    }

    const notifications = await this.directusClient.request(
      readItems('notifications', {
        filter: {
          userId: { _eq: userId },
          read: { _eq: false },
          createdAt: { _gte: cutoffTime.toISOString() }
        },
        sort: ['-priority', '-createdAt']
      })
    );

    return notifications;
  }

  /**
   * Mark notifications as emailed
   */
  private async markNotificationsAsEmailed(notificationIds: string[]): Promise<void> {
    for (const id of notificationIds) {
      await this.directusClient.request(
        updateItem('notifications', id, {
          emailedAt: new Date().toISOString()
        })
      );
    }
  }

  /**
   * Clean up old notifications
   */
  async cleanupOldNotifications(daysToKeep: number = 30): Promise<number> {
    const cutoffDate = new Date();
    cutoffDate.setDate(cutoffDate.getDate() - daysToKeep);

    try {
      // Get old notifications
      const oldNotifications = await this.directusClient.request(
        readItems('notifications', {
          filter: {
            createdAt: { _lt: cutoffDate.toISOString() },
            read: { _eq: true }
          },
          fields: ['id']
        })
      );

      // Delete them
      for (const notification of oldNotifications) {
        await this.directusClient.request(
          directusSdk.deleteItem('notifications', notification.id)
        );
      }

      console.log(`Cleaned up ${oldNotifications.length} old notifications`);
      return oldNotifications.length;
    } catch (error) {
      console.error('Failed to cleanup old notifications:', error);
      return 0;
    }
  }
}

// Export singleton instance
export const notificationService = new NotificationService();