import { Environment } from './provisioning-node.model';

/**
 * Partner API credentials.
 * Per docs/backend/PARTNER-PROVISIONING-API-CONTRACT.md §6, TRACK-S §4.1.
 *
 * The partner generates the keypair. We hold only the PUBLIC key - the
 * private half is never transmitted to us, never accepted by any endpoint,
 * never logged. There is deliberately no field for it in this model, so no
 * UI or gateway can accidentally carry one.
 */

export type CredentialAlgorithm = 'ed25519' | 'rsa-pss-sha256';

/** `rotating` means a successor key is registered and both currently verify. */
export type CredentialStatus = 'active' | 'rotating' | 'revoked';

export interface PartnerCredential {
  partnerId: string;
  keyId: string;
  /** Authority is this node's subtree - nothing above it, nothing beside it. */
  scopeNodeId: string;
  environment: Environment;
  algorithm: CredentialAlgorithm;
  /** PEM or base64 raw, per algorithm. Public half only. */
  publicKey: string;
  status: CredentialStatus;
  createdAt: string;
  expiresAt?: string;
}

export interface RegisterCredentialRequest {
  scopeNodeId: string;
  environment: Environment;
  algorithm: CredentialAlgorithm;
  publicKey: string;
}

/**
 * Revocation is immediate and irreversible (§6.2); a revoked credential can
 * never be rotated back into service. Rotation only applies to a live key.
 */
export function canRotate(credential: PartnerCredential): boolean {
  return credential.status === 'active';
}

export function canRevoke(credential: PartnerCredential): boolean {
  return credential.status !== 'revoked';
}

/**
 * Guards against a private key being pasted into a public-key field. Not a
 * validity check on the key itself - that is the backend's job - purely a
 * "this is the wrong half" check, because the cost of getting it wrong is a
 * partner's private key landing in our logs.
 */
export function looksLikePrivateKey(value: string): boolean {
  return /PRIVATE KEY|BEGIN OPENSSH PRIVATE/i.test(value);
}
