import { HttpClient, HttpParams } from '@angular/common/http';
import { Injectable, inject } from '@angular/core';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { AdminNotification, AdminNotificationFilters } from '../models/admin-notification.model';
import { AdminNotificationsGateway } from './admin-notifications-gateway.interface';

/** Contract: docs/backend/PHASE-2-ORDERS-NOTIFICATIONS-CONTRACT.md §7. */
@Injectable({ providedIn: 'root' })
export class AdminNotificationsApiGateway implements AdminNotificationsGateway {
  private readonly http = inject(HttpClient);

  loadNotifications(filters: AdminNotificationFilters): Observable<AdminNotification[]> {
    let params = new HttpParams();
    for (const [key, value] of Object.entries(filters ?? {})) {
      if (value !== undefined && value !== null && value !== '') {
        params = params.set(key, String(value));
      }
    }
    return this.http.get<AdminNotification[]>('/api/admin/v2/notifications', { params });
  }

  markRead(id: string): Observable<void> {
    return this.http
      .patch(`/api/admin/v2/notifications/${encodeURIComponent(id)}/read`, {})
      .pipe(map(() => undefined));
  }

  markAllRead(): Observable<void> {
    // Contract documents per-notification PATCH .../{id}/read only; a bulk
    // endpoint isn't specified. Inferred at the collection path pending that
    // being defined - revisit if the backend does this differently.
    return this.http
      .patch('/api/admin/v2/notifications/read-all', {})
      .pipe(map(() => undefined));
  }
}
