import { AppNotification, NotificationType, NotificationPriority, NotificationPayload } from '../types/notifications';

// Mock data for initial state
const MOCK_NOTIFICATIONS: AppNotification[] = [
  {
    id: 'notif-1',
    tenantId: 'W1',
    recipientId: '901', // demo_admin
    actorId: '905', // demo_mechaniker
    type: 'LEAVE_REQUEST_CREATED',
    title: 'Neuer Urlaubsantrag',
    message: 'Max Mustermann hat einen Urlaubsantrag für den 15.08. - 25.08. eingereicht.',
    priority: 'MEDIUM',
    isRead: false,
    createdAt: new Date(Date.now() - 1000 * 60 * 30).toISOString(), // 30 mins ago
    payload: {
      entityId: 'leave-req-1',
      entityType: 'LEAVE_REQUEST'
    }
  },
  {
    id: 'notif-2',
    tenantId: 'W1',
    recipientId: '901',
    type: 'SYSTEM_ALERT',
    title: 'System Update',
    message: 'Das System wird heute Nacht um 02:00 Uhr gewartet.',
    priority: 'LOW',
    isRead: false,
    createdAt: new Date(Date.now() - 1000 * 60 * 60 * 24).toISOString(), // 1 day ago
  }
];

const STORAGE_KEY = 'cms_notifications';

class NotificationService {
  private getStoredNotifications(): AppNotification[] {
    const stored = localStorage.getItem(STORAGE_KEY);
    if (stored) {
      return JSON.parse(stored);
    }
    // Initialize with mock data if empty
    localStorage.setItem(STORAGE_KEY, JSON.stringify(MOCK_NOTIFICATIONS));
    return MOCK_NOTIFICATIONS;
  }

  private saveNotifications(notifications: AppNotification[]) {
    localStorage.setItem(STORAGE_KEY, JSON.stringify(notifications));
  }

  async getNotifications(userId: string, tenantId: string): Promise<AppNotification[]> {
    // Simulate network delay
    await new Promise(resolve => setTimeout(resolve, 300));
    const all = this.getStoredNotifications();
    return all
      .filter(n => n.recipientId === userId && n.tenantId === tenantId)
      .sort((a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime());
  }

  async markAsRead(notificationId: string): Promise<void> {
    await new Promise(resolve => setTimeout(resolve, 100));
    const all = this.getStoredNotifications();
    const updated = all.map(n => n.id === notificationId ? { ...n, isRead: true } : n);
    this.saveNotifications(updated);
  }

  async markAllAsRead(userId: string): Promise<void> {
    await new Promise(resolve => setTimeout(resolve, 100));
    const all = this.getStoredNotifications();
    const updated = all.map(n => 
      (n.recipientId === userId) 
        ? { ...n, isRead: true } 
        : n
    );
    this.saveNotifications(updated);
  }

  async markByEntityAsRead(entityId: string, entityType: string, userId?: string): Promise<void> {
    await new Promise(resolve => setTimeout(resolve, 100));
    const all = this.getStoredNotifications();
    const updated = all.map(n => 
      (n.payload?.entityId === entityId && n.payload?.entityType === entityType && (!userId || n.recipientId === userId)) 
        ? { ...n, isRead: true } 
        : n
    );
    this.saveNotifications(updated);
  }

  async createNotification(
    tenantId: string,
    recipientId: string,
    type: NotificationType,
    title: string,
    message: string,
    priority: NotificationPriority = 'LOW',
    actorId?: string,
    payload?: NotificationPayload
  ): Promise<AppNotification> {
    const newNotification: AppNotification = {
      id: `notif-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`,
      tenantId,
      recipientId,
      actorId,
      type,
      title,
      message,
      priority,
      isRead: false,
      createdAt: new Date().toISOString(),
      payload
    };

    const all = this.getStoredNotifications();
    this.saveNotifications([newNotification, ...all]);
    return newNotification;
  }
}

export const notificationService = new NotificationService();
