import { Injectable, inject, resource } from '@angular/core';
import { Result, ok, err } from '@shared/kernel/fp';
import { BrpAddressDto } from '@registratie/contracts/brp-address.dto';
import { ApiClient } from '@shared/infrastructure/api-client';

/**
 * Infrastructure adapter for the BRP address lookup, reached only through our own
 * ("BFF-lite") endpoint — the anti-corruption boundary. Data comes from the .NET
 * backend (`GET /api/brp/address`) via the generated typed client.
 */
@Injectable({ providedIn: 'root' })
export class BrpAdapter {
  private client = inject(ApiClient);

  // The value is untrusted JSON until parseBrpAddress validates it.
  adresResource() {
    return resource({ loader: () => this.client.address() });
  }
}

/** Trust-boundary parse: validate the untrusted response shape. "Geen adres" is a
    valid outcome (gevonden: false), not a malformed response. ponytail: hand-written;
    reach for a schema lib once the contract count grows. */
export function parseBrpAddress(json: unknown): Result<string, BrpAddressDto> {
  if (typeof json !== 'object' || json === null) return err('brp-address: not an object');
  const dto = json as Partial<BrpAddressDto>;
  if (typeof dto.gevonden !== 'boolean') return err('brp-address: missing/invalid gevonden');
  if (dto.gevonden) {
    const a = dto.adres;
    if (
      !a ||
      typeof a.straat !== 'string' ||
      typeof a.postcode !== 'string' ||
      typeof a.woonplaats !== 'string'
    ) {
      return err('brp-address: missing/invalid adres');
    }
  }
  return ok({ gevonden: dto.gevonden, adres: dto.adres });
}
