import { HttpClient, HttpParams } from '@angular/common/http';
import { Injectable, inject } from '@angular/core';
import { Observable } from 'rxjs';
import { AdminTransaction, AdminTransactionListFilters, AdminTransactionsListResult } from '../models/admin-transaction.model';
import { AdminTransactionsGateway } from './admin-transactions-gateway.interface';

/**
 * No dedicated transactions contract doc exists yet - this reads as the
 * admin-facing view of Payment/PaymentEvent from
 * docs/backend/PHASE-1-MONEY-FX-PAYMENTS-CONTRACT.md §6, at the
 * conventional /api/admin/v2/{resource} path used throughout that contract set.
 */
@Injectable({ providedIn: 'root' })
export class AdminTransactionsApiGateway implements AdminTransactionsGateway {
  private readonly http = inject(HttpClient);

  loadTransactions(filters: AdminTransactionListFilters): Observable<AdminTransactionsListResult> {
    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<AdminTransactionsListResult>('/api/admin/v2/transactions', { params });
  }

  retryFailed(id: string): Observable<AdminTransaction | null> {
    return this.http.post<AdminTransaction | null>(`/api/admin/v2/transactions/${encodeURIComponent(id)}/retry`, {});
  }

  setFraudFlag(id: string, flagged: boolean): Observable<AdminTransaction | null> {
    return this.http.patch<AdminTransaction | null>(`/api/admin/v2/transactions/${encodeURIComponent(id)}`, { flagged });
  }
}
