import { HttpClient, HttpParams } from '@angular/common/http';
import { Injectable, inject } from '@angular/core';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { ReconciliationRecord, Refund, Settlement } from '../models/reconciliation.model';
import { FinanceGateway } from './finance-gateway.interface';

/** Contract: docs/backend/PHASE-7-PAYMENTS-RECONCILIATION-CONTRACT.md §1-3. */
@Injectable({ providedIn: 'root' })
export class FinanceApiGateway implements FinanceGateway {
  private readonly http = inject(HttpClient);

  loadRefunds(orderId?: string): Observable<Refund[]> {
    // §1: refunds are scoped to one order (POST/GET .../orders/{orderId}/refunds).
    // Without an orderId there is no single-order endpoint to call; return
    // empty rather than guess at a global refunds list the contract doesn't define.
    if (!orderId) {
      return new Observable<Refund[]>(subscriber => {
        subscriber.next([]);
        subscriber.complete();
      });
    }
    return this.http.get<Refund[]>(`/api/admin/v2/orders/${encodeURIComponent(orderId)}/refunds`);
  }

  loadReconciliationQueue(): Observable<ReconciliationRecord[]> {
    return this.http.get<ReconciliationRecord[]>('/api/admin/v2/reconciliation/queue');
  }

  resolveReconciliation(id: string, note: string): Observable<void> {
    return this.http
      .post(`/api/admin/v2/reconciliation/${encodeURIComponent(id)}/resolve`, { note })
      .pipe(map(() => undefined));
  }

  loadSettlements(sellerId?: string): Observable<Settlement[]> {
    const params = sellerId ? new HttpParams().set('sellerId', sellerId) : undefined;
    return this.http.get<Settlement[]>('/api/admin/v2/finance/settlements', { params });
  }
}
