import apiService from './apiService';

export interface Notification {
  name: string;
  for_user: string;
  subject?: string;
  email_content?: string;
  document_type?: string;
  document_name?: string;
  read: number;
  creation: string;
  type?: string;
  from_user?: string;
}

class NotificationService {
  /**
   * Get notifications for current user
   */
  async getNotifications(limit: number = 50, offset: number = 0) {
    const user = localStorage.getItem('user');
    const userEmail = user ? JSON.parse(user).email : '';
    
    if (!userEmail) {
      return [];
    }

    try {
      const filters = JSON.stringify([['for_user', '=', userEmail]]);
      const fields = JSON.stringify(['name', 'subject', 'email_content', 'document_type', 'document_name', 'read', 'creation', 'from_user', 'type']);
      
      const response = await apiService.apiCall<any>(
        `/api/resource/Notification Log?filters=${encodeURIComponent(filters)}&fields=${encodeURIComponent(fields)}&order_by=creation desc&limit=${limit}&offset=${offset}`
      );
      
      console.log('[NotificationService] Fetched notifications:', response?.data);
      if (response?.data?.length > 0) {
        console.log('[NotificationService] First notification sample:', response.data[0]);
      }
      
      return response?.data || [];
    } catch (error: any) {
      // 417 (Expectation Failed) is common when Notification doctype isn't accessible via resource API
      // Silently return empty array - notifications feature will be disabled
      if (error?.message?.includes('417') || error?.message?.includes('EXPECTATION FAILED')) {
        return [];
      }
      // Only log non-417 errors
      if (!error?.message?.includes('417')) {
        console.warn('Notifications API not available:', error?.message || 'Unknown error');
      }
      return [];
    }
  }

  /**
   * Mark notification as read
   */
  async markAsRead(notificationName: string) {
    try {
      return await apiService.apiCall(
        `/api/resource/Notification Log/${notificationName}`,
        {
          method: 'PUT',
          body: JSON.stringify({ read: 1 })
        }
      );
    } catch (error: any) {
      // Silently handle 417 errors (API not available) or permission errors
      if (error?.message?.includes('417') || 
          error?.message?.includes('EXPECTATION FAILED') ||
          error?.message?.includes('PermissionError') ||
          error?.message?.includes('Insufficient Permission')) {
        console.warn('[NotificationService] Cannot mark as read (permissions)');
        return { success: false, reason: 'permission_denied' };
      }
      console.warn('Error marking notification as read:', error?.message || 'Unknown error');
      throw error;
    }
  }

  /**
   * Mark all notifications as read
   */
  async markAllAsRead() {
    try {
      const notifications = await this.getNotifications(1000);
      const unread = notifications.filter(n => !n.read);
      
      let markedCount = 0;
      for (const notif of unread) {
        try {
          const result = await this.markAsRead(notif.name);
          if (result?.success !== false) {
            markedCount++;
          }
        } catch (error) {
          // Continue with other notifications even if one fails
          console.error(`Error marking notification ${notif.name} as read:`, error);
        }
      }
      
      return { success: true, marked: markedCount, total: unread.length };
    } catch (error) {
      console.error('Error marking all notifications as read:', error);
      // Don't throw - return a failed result instead
      return { success: false, marked: 0, total: 0 };
    }
  }

  /**
   * Get unread count
   */
  async getUnreadCount(): Promise<number> {
    try {
      const notifications = await this.getNotifications(1000);
      return notifications.filter(n => !n.read).length;
    } catch (error) {
      console.error('Error getting unread count:', error);
      return 0;
    }
  }
}

export default new NotificationService();


