import { HttpClient, HttpParams } from '@angular/common/http';
import { Injectable, inject } from '@angular/core';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { AdminOrder, AdminOrderListFilters, AdminOrdersListResult, AdminOrderStatus } from '../models/admin-order.model';
import { AdminOrdersGateway } from './admin-orders-gateway.interface';

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

  loadOrders(filters: AdminOrderListFilters): Observable<AdminOrdersListResult> {
    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<AdminOrdersListResult>('/api/admin/v2/orders', { params });
  }

  loadOrder(id: string): Observable<AdminOrder | null> {
    return this.http.get<AdminOrder | null>(`/api/admin/v2/orders/${encodeURIComponent(id)}`);
  }

  updateStatus(id: string, status: AdminOrderStatus): Observable<AdminOrder | null> {
    return this.http.patch<AdminOrder | null>(`/api/admin/v2/orders/${encodeURIComponent(id)}/status`, { status });
  }

  requestRefund(id: string): Observable<AdminOrder | null> {
    return this.http.post<AdminOrder | null>(`/api/admin/v2/orders/${encodeURIComponent(id)}/refund-request`, {});
  }

  addNote(id: string, note: string, internal: boolean): Observable<AdminOrder | null> {
    return this.http.post<AdminOrder | null>(`/api/admin/v2/orders/${encodeURIComponent(id)}/notes`, { note, internal });
  }

  archiveOrder(id: string): Observable<AdminOrder | null> {
    return this.http.post<AdminOrder | null>(`/api/admin/v2/orders/${encodeURIComponent(id)}/archive`, {});
  }

  restoreOrder(id: string): Observable<AdminOrder | null> {
    return this.http.post<AdminOrder | null>(`/api/admin/v2/orders/${encodeURIComponent(id)}/restore`, {});
  }

  deleteOrder(id: string): Observable<void> {
    return this.http.delete(`/api/admin/v2/orders/${encodeURIComponent(id)}`).pipe(map(() => undefined));
  }
}
