import { HttpClient } from '@angular/common/http';
import { inject, Injectable } from '@angular/core';
import { environment } from 'environments/environment';
import type { Observable } from 'rxjs';

/**
 * Establishes a hub session by posting the freshly-issued access token
 * to the backend session endpoint (`POST <backend>/o-auth/session`).
 *
 * The backend verifies the token and responds with a `Set-Cookie: hub_session`
 * (httpOnly). `withCredentials: true` is mandatory so the browser accepts
 * the cookie on a cross-origin response (frontend :4200 → backend :3000 in dev).
 *
 * The URL is built from `environment.api.rest` (the absolute REST base URL) so
 * the request always targets the backend origin — never the frontend origin.
 * A relative URL like '/api/o-auth/session' would resolve against the Angular
 * dev server, which never sets the cookie on the backend and causes the
 * continue-flow to dead-loop.
 *
 * After calling `establishSession`, the caller should navigate the browser to the
 * OAuth `/authorize` URL using `window.location.href` (full-page navigation) so
 * the browser includes the newly-set `hub_session` cookie in the redirect.
 */
@Injectable({
  providedIn: 'root',
})
export class OAuthSessionService {
  private readonly http = inject(HttpClient);

  /**
   * POST the access token to the session-establishment endpoint.
   *
   * URL: `environment.api.rest` + `/o-auth/session`.
   * Example: `http://localhost:8080/api/o-auth/session`.
   *
   * @param accessToken - The freshly issued access token from the Password grant.
   * @returns An Observable that completes when the backend responds (204 No Content).
   */
  establishSession(accessToken: string): Observable<unknown> {
    const sessionUrl = `${environment.api.rest}/o-auth/session`;
    return this.http.post(sessionUrl, { access_token: accessToken }, { withCredentials: true });
  }
}
