/** Defensive accessors for loosely-typed projection payloads. */
import type { ProjectionRecord } from "../api/schemas";

export function asRecord(value: unknown): Record<string, unknown> | null {
  return value !== null && typeof value === "object" && !Array.isArray(value)
    ? (value as Record<string, unknown>)
    : null;
}

export function asString(value: unknown): string | null {
  return typeof value === "string" ? value : null;
}

export function asNumber(value: unknown): number | null {
  return typeof value === "number" && Number.isFinite(value) ? value : null;
}

export function asArray(value: unknown): unknown[] {
  return Array.isArray(value) ? value : [];
}

/**
 * Extract the CMS wrapper's EE certificate from a parsed projection, if any.
 * Real shape: projection.object.signedObject.signedData.certificates[] — each
 * entry carries a `resourceCertificate` with `kind: "Ee"` for the signer cert.
 * Returns a `{ resourceCertificate }` projection for CertificateView, or null
 * when the object is not CMS-signed or has no embedded certificate.
 */
export function eeCertificateProjection(
  record: ProjectionRecord | null,
): Record<string, unknown> | null {
  const projection = record?.projection;
  if (!projection || record?.parseStatus === "error") return null;
  const typed = asRecord(projection.object) ?? projection;
  const certificates = asArray(asRecord(asRecord(typed.signedObject)?.signedData)?.certificates);
  const certs = certificates
    .map((entry) => asRecord(asRecord(entry)?.resourceCertificate))
    .filter((cert): cert is Record<string, unknown> => Boolean(cert));
  if (!certs.length) return null;
  const ee = certs.find((cert) => asString(cert.kind) === "Ee") ?? certs[0];
  return { resourceCertificate: ee };
}
