import { computed, inject, Injectable, signal } from '@angular/core';
import { CurrentAccountService } from '@aurora';
import { type IamAccount } from '@src/src/app/aurora.types';
import { Apollo } from 'apollo-angular';
import { catchError, of } from 'rxjs';
import { meAccountQuery } from './account.graphql';

/**
 * IAM adapter for the `CurrentAccountService` port: loads the authenticated account via the IAM
 * `iamMeAccount` query and exposes it as display-ready signals. Wired in `aurora.provider.ts`.
 * Best-effort: a failed load leaves the signals blank so the shell renders a neutral placeholder.
 */
@Injectable()
export class CurrentAccountIamAdapter extends CurrentAccountService {
  private readonly apollo = inject(Apollo);
  private readonly account = signal<IamAccount | null>(null);

  readonly displayName = computed(() => {
    const account = this.account();
    if (!account) return '';
    const name = account.user?.name;
    if (name) return account.user?.surname ? `${name} ${account.user.surname}` : name;
    return account.username ?? '';
  });

  readonly email = computed(() => this.account()?.email ?? '');

  load(): void {
    this.apollo
      .query<{ iamMeAccount: IamAccount }>({ query: meAccountQuery })
      .pipe(catchError(() => of(null)))
      .subscribe((result) => this.account.set(result?.data?.iamMeAccount ?? null));
  }
}
