import { HttpClient } from '@angular/common/http';
import { Injectable, inject } from '@angular/core';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { Connector, DeadLetterEntry } from '../models/connector.model';
import { ConnectorGateway } from './connector-gateway.interface';

/** Contract: docs/backend/PHASE-4-CONNECTOR-FRAMEWORK-CONTRACT.md §7-8. */
@Injectable({ providedIn: 'root' })
export class ConnectorApiGateway implements ConnectorGateway {
  private readonly http = inject(HttpClient);

  loadConnectors(): Observable<Connector[]> {
    return this.http.get<Connector[]>('/api/admin/v2/integrations');
  }

  loadDeadLetter(connectorId: string): Observable<DeadLetterEntry[]> {
    // §7 defines dead-letter replay (POST .../dead-letter/{id}/replay) but not
    // a GET list endpoint - inferred at the same collection path, consistent
    // with the rest of this contract's REST conventions.
    return this.http.get<DeadLetterEntry[]>(
      `/api/admin/v2/integrations/${encodeURIComponent(connectorId)}/dead-letter`,
    );
  }

  replay(connectorId: string, deadLetterId: string): Observable<void> {
    return this.http
      .post(
        `/api/admin/v2/integrations/${encodeURIComponent(connectorId)}/dead-letter/${encodeURIComponent(deadLetterId)}/replay`,
        {},
      )
      .pipe(map(() => undefined));
  }

  pause(connectorId: string): Observable<void> {
    return this.http
      .patch(`/api/admin/v2/integrations/${encodeURIComponent(connectorId)}`, { status: 'paused' })
      .pipe(map(() => undefined));
  }

  resume(connectorId: string): Observable<void> {
    return this.http
      .patch(`/api/admin/v2/integrations/${encodeURIComponent(connectorId)}`, { status: 'active' })
      .pipe(map(() => undefined));
  }
}
