/**
 * Cryptographic utilities for SentryAgent.ai AgentIdP.
 * Handles client secret generation and bcrypt hashing.
 */

import crypto from 'crypto';
import bcrypt from 'bcryptjs';

const BCRYPT_ROUNDS = 10;
const SECRET_PREFIX = 'sk_live_';
const SECRET_RANDOM_BYTES = 32;

/**
 * Generates a new client secret with the `sk_live_` prefix followed by 64 hex chars
 * (32 random bytes = 256 bits of entropy).
 *
 * @returns Plain-text client secret in the format `sk_live_<64 hex chars>`.
 */
export function generateClientSecret(): string {
  const randomBytes = crypto.randomBytes(SECRET_RANDOM_BYTES);
  return `${SECRET_PREFIX}${randomBytes.toString('hex')}`;
}

/**
 * Hashes a plain-text secret using bcrypt with 10 rounds.
 *
 * @param plain - The plain-text secret to hash.
 * @returns Promise resolving to the bcrypt hash string.
 */
export async function hashSecret(plain: string): Promise<string> {
  return bcrypt.hash(plain, BCRYPT_ROUNDS);
}

/**
 * Verifies a plain-text secret against a stored bcrypt hash.
 *
 * @param plain - The plain-text secret provided by the client.
 * @param hash - The bcrypt hash stored in the database.
 * @returns Promise resolving to `true` if the secret matches, `false` otherwise.
 */
export async function verifySecret(plain: string, hash: string): Promise<boolean> {
  return bcrypt.compare(plain, hash);
}
