import { Injectable, inject } from '@angular/core';
import { Observable, map, of } from 'rxjs';
import { AdminNotification, AdminNotificationFilters } from '../models/admin-notification.model';
import { AdminNotificationsGateway } from './admin-notifications-gateway.interface';
import { ADMIN_ORDERS_GATEWAY } from '../../orders/services/admin-orders-gateway.token';

/**
 * Derives notifications from the existing (mock) Orders gateway so the shape
 * is real even before a platform event bus exists. Once
 * docs/backend/PHASE-2-ORDERS-NOTIFICATIONS-CONTRACT.md §6 ships, swap the
 * token - no caller changes needed.
 */
@Injectable({ providedIn: 'root' })
export class AdminNotificationsLocalGateway implements AdminNotificationsGateway {
  private readonly ordersGateway = inject(ADMIN_ORDERS_GATEWAY);
  private readonly readIds = new Set<string>();

  loadNotifications(filters: AdminNotificationFilters): Observable<AdminNotification[]> {
    return this.ordersGateway.loadOrders({ search: '', status: 'all', page: 1, pageSize: 20 }).pipe(
      map(result => result.items
        .map((order): AdminNotification => ({
          id: `notif_${order.id}`,
          marketplaceId: 'default',
          entityType: 'order',
          entityId: order.id,
          severity: order.status === 'cancelled' ? 'warning' : 'info',
          eventType: order.payment.status === 'paid' ? 'order.paid' : 'order.created',
          title: `Order ${order.orderNumber} - ${order.payment.status === 'paid' ? 'paid' : 'created'}`,
          read: this.readIds.has(order.id),
          deepLink: ['orders', order.id],
          createdAt: order.createdAt,
        }))
        .filter(n => !filters.unreadOnly || !n.read)
        .filter(n => !filters.eventType || filters.eventType === 'all' || n.eventType === filters.eventType)
      )
    );
  }

  markRead(id: string): Observable<void> {
    const orderId = id.replace(/^notif_/, '');
    this.readIds.add(orderId);
    return of(void 0);
  }

  markAllRead(): Observable<void> {
    return this.loadNotifications({ marketplaceId: '', eventType: '', unreadOnly: false }).pipe(
      map(items => { items.forEach(n => this.readIds.add(n.entityId)); })
    );
  }
}
