import { Injectable, inject, resource } from '@angular/core';
import { Result, ok, err } from '@shared/kernel/fp';
import { Capability } from '@shared/domain/capability';
import { ApiClient } from '@shared/infrastructure/api-client';

const KNOWN: readonly Capability[] = [
  'brief:approve',
  'brief:reject',
  'brief:send',
  'orgtemplate:edit',
];

/**
 * Infrastructure adapter for `GET /me` (PRD-0002 §6): the current principal's
 * coarse, role-derived capabilities — nav/menu-level, not tied to any one screen's
 * live status (contrast a screen's own decision DTO, e.g. `BriefViewDto.decisions`).
 */
@Injectable({ providedIn: 'root' })
export class MeAdapter {
  private client = inject(ApiClient);

  meResource() {
    return resource({ loader: () => this.client.me() });
  }
}

/**
 * Trust-boundary parse. An unrecognized capability string is dropped rather than
 * rejecting the whole response — deny-by-default already covers it (AccessStore.can
 * returns false for anything not in the set), and it lets the backend grow the
 * capability list without breaking an older FE build.
 */
export function parseMe(json: unknown): Result<string, Capability[]> {
  if (typeof json !== 'object' || json === null) return err('me: not an object');
  const dto = json as { capabilities?: unknown };
  if (!Array.isArray(dto.capabilities)) return err('me: missing/invalid capabilities');
  return ok(dto.capabilities.filter((c): c is Capability => KNOWN.includes(c as Capability)));
}
