/**
 * Backup destination transport contract + per-type config shapes.
 * See docs/superpowers/specs/2026-06-04-backup-destinations-design.md.
 *
 * Config shapes here are the *decrypted, runtime* form. Secrets are stored
 * AES-GCM-encrypted in the `backup_destinations.config` jsonb and decrypted by
 * the service layer before a transport is constructed.
 */

export type BackupDestinationType = 'sftp' | 's3' | 'filesystem';

/** Filename prefix every full-bundle tar carries (`createFullBackupTar`). */
export const BACKUP_NAME_PREFIX = 'pn-crm-backup-';

export interface BackupTransport {
  /** Verify the destination is reachable + writable. Throws on failure. */
  test(): Promise<void>;
  /** Upload `localPath` to the destination as `remoteName`. */
  push(localPath: string, remoteName: string): Promise<{ remoteRef: string; bytes: number }>;
  /** Keep the `retentionCount` newest bundles; null = keep all. */
  prune(retentionCount: number | null): Promise<{ deleted: number }>;
}

export interface FilesystemDestConfig {
  /** Absolute path to a mounted volume / NAS directory the app can write to. */
  directory: string;
}

export interface SftpDestConfig {
  host: string;
  port?: number;
  username: string;
  /** One of password / privateKey is required. */
  password?: string;
  privateKey?: string;
  /** Passphrase for an encrypted private key. */
  passphrase?: string;
  remoteDir: string;
  /** Optional pinned host-key fingerprint (sha256 hex). When set, the
   *  connection is rejected unless the server's key matches. */
  hostFingerprint?: string;
}

export interface S3DestConfig {
  endpoint: string;
  region?: string;
  bucket: string;
  accessKey: string;
  secretKey: string;
  /** Key prefix within the bucket (e.g. "crm-backups/"). */
  prefix?: string;
  /** Default true; set false only for pl-text local MinIO test endpoints. */
  useSSL?: boolean;
  port?: number;
}

/** Sort backup bundle filenames newest-first (timestamp-in-name sorts lexically). */
export function sortBundlesNewestFirst(names: string[]): string[] {
  return names.filter((n) => n.startsWith(BACKUP_NAME_PREFIX)).sort((a, b) => b.localeCompare(a));
}
