import { computed, Injectable, signal } from '@angular/core';
import { CREDENTIALS_KEY, readCredentials } from './authentication';
import type { OAuthTokens } from './authentication.types';

/**
 * Holds the credentials/accessToken/refreshToken signals and owns the
 * localStorage I/O for the authentication session. Deliberately has zero
 * Apollo dependency so it can be injected by the Apollo factory without
 * creating the apolloFactory ↔ AuthenticationService ↔ Apollo cycle.
 *
 * State writers (`signIn`, `signOut`, etc.) live on `AuthenticationService`
 * and delegate to this store. Read-only consumers (route guards, components
 * that gate UI on `authenticated`, the Apollo factory's `SetContextLink`)
 * inject this store directly.
 */
@Injectable()
export class TokenStore {
  private readonly _credentials = signal<OAuthTokens | null>(readCredentials());

  readonly authenticated = computed(() => this._credentials() !== null);
  readonly accessToken = computed(() => this._credentials()?.accessToken ?? '');
  readonly refreshToken = computed(() => this._credentials()?.refreshToken ?? '');

  setCredentials(credentials: OAuthTokens): void {
    localStorage.setItem(CREDENTIALS_KEY, btoa(JSON.stringify(credentials)));
    this._credentials.set(credentials);
  }

  getCredentials(): OAuthTokens | null {
    return this._credentials();
  }

  clear(): void {
    localStorage.removeItem(CREDENTIALS_KEY);
    this._credentials.set(null);
  }
}
