import { Injectable, inject, resource } from '@angular/core';
import { Result, ok, err } from '@shared/kernel/fp';
import { Aantekening, AantekeningType } from '../domain/registration';
import { ApiClient, AantekeningDto } from '@shared/infrastructure/api-client';

/**
 * Infrastructure adapter for the BIG-register source. Exposes signal-based
 * resources (Angular's `resource` over the generated typed client); each returns
 * a Resource with status()/value()/error()/reload(). Call from an injection
 * context (a field initializer in the store).
 *
 * Note: registration + person are now served via the aggregated dashboard-view
 * endpoint (see DashboardViewAdapter). Only the notes stream remains separate.
 */
@Injectable({ providedIn: 'root' })
export class BigRegisterAdapter {
  private client = inject(ApiClient);

  aantekeningenResource() {
    return resource({
      loader: () =>
        this.client.notes().then((ns) => {
          const out: Aantekening[] = [];
          for (const n of ns) {
            const parsed = parseAantekening(n);
            if (!parsed.ok) throw new Error(parsed.error);
            out.push(parsed.value);
          }
          return out;
        }),
    });
  }
}

const AANTEKENING_TYPES: readonly AantekeningType[] = ['Specialisme', 'Aantekening'];

/** Trust-boundary parse: an unrecognized type is an explicit Failure, never a silent cast. */
export function parseAantekening(n: AantekeningDto): Result<string, Aantekening> {
  if (!n.type || !AANTEKENING_TYPES.includes(n.type as AantekeningType))
    return err(`aantekening: unknown type ${n.type}`);
  return ok({
    type: n.type as AantekeningType,
    omschrijving: n.omschrijving ?? '',
    datum: n.datum ?? '',
  });
}
