import { HttpClient, HttpParams } from '@angular/common/http';
import { Injectable, inject } from '@angular/core';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { ExternalIdentity, ExternalIdentityProvider } from '../models/customer-identity.model';
import { SocialIdentityGateway, SocialProvider } from './social-identity-gateway.interface';

/**
 * Contract: docs/backend/PHASE-8-IDENTITY-MESSAGING-CONTRACT.md §2.
 *
 * Provider-agnostic by construction - VK ID and Yandex ID differ only in the
 * path segment, because the differences that matter (PKCE, VK's device_id,
 * Yandex's Basic-auth token exchange) live entirely on the backend.
 */
@Injectable({ providedIn: 'root' })
export class SocialIdentityApiGateway implements SocialIdentityGateway {
  private readonly http = inject(HttpClient);
  private readonly base = '/api/identity/v1';

  getAuthorizeUrl(provider: SocialProvider, returnTo?: string): Observable<string> {
    const params = returnTo ? new HttpParams().set('returnTo', returnTo) : undefined;
    return this.http
      .get<{ url: string }>(`${this.base}/${provider}/authorize`, { params })
      .pipe(map(response => response.url));
  }

  listIdentities(): Observable<ExternalIdentity[]> {
    return this.http.get<ExternalIdentity[]>(`${this.base}/me/identities`);
  }

  unlink(provider: ExternalIdentityProvider): Observable<void> {
    return this.http.post<void>(`${this.base}/${provider}/unlink`, {});
  }
}
